【发布时间】:2021-08-25 20:53:12
【问题描述】:
我正在尝试创建一个执行一些计算的多线程程序。这是我正在尝试做的一个示例:
#include <list>
#include <iostream>
#include <thread>
using namespace std;
mutex mtx;
class fire {
public:
int th;
fire(int thr) {
this->th = thr;
}
void execute() {
for(int x = 0; x < 10; x++) {
mtx.lock();
cout << "thread : " << this->th << " loop : " << x << endl;
mtx.unlock();
}
}
thread exec() {
cout << "Execute\n";
return thread([=] { execute(); } );
}
};
int main(void) {
list<fire> move;
for(int x = 0; x < 8; x++) {
move.push_back(fire(x));
}
for ( auto x : move) {
thread z = x.exec();
z.detach();
}
cout << "End\n";
}
输出是:
Execute
Execute
Execute
thread : 2 loop : 0
thread : 2 loop : 1
thread : 2 loop : 2
thread : 2 loop : 3
thread : 2 loop : 4
thread : 2 loop : 5
thread : 2 loop : 6
thread : 2 loop : 7
thread : 2 loop : 8
thread : 2 loop : 9
Execute
thread : 3 loop : 0
thread : 3 loop : 1
thread : Execute
4 loop : 2
thread : 4 loop : 3
Execute
thread : 5 loop : 0
thread : 5 loop : 1
Execute
Execute
End
如您所见,这不是预期的行为,我已经厌倦了 Google 搜索。 为什么我在这段简单的代码中看不到正常行为?
【问题讨论】:
-
如果你分离线程,那么线程将不能保证运行完成;当 main() 返回并且进程被销毁时,它们将被终止。为避免这种情况,您不应分离它们;而是在 main() 的末尾添加一个额外的 for 循环,在每个线程上调用 join()。
-
您希望程序继续运行直到所有线程完成吗?如果是这样,您需要在
main中致电pthread_exit。从main返回会终止进程。
标签: c++ multithreading c++11