首页 > 解决方案 > 运行多个分离线程的意外行为

问题描述

我正在尝试创建一个执行一些计算的多线程程序。这是我正在尝试做的一个例子:

#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 搜索感到筋疲力尽。为什么我没有从这段简单的代码中看到正常行为?

标签: c++multithreadingc++11

解决方案


你忘了pthread_exit在结束时打电话main。从main终止进程返回,不给分离的线程运行时间。

但作为一般规则,最好不要分离线程。


推荐阅读