【问题标题】:Unexpected behavior running multiple detached threads运行多个分离线程的意外行为
【发布时间】: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


【解决方案1】:

您忘记在main 末尾拨打pthread_exit。从main 返回会终止进程,不给分离的线程运行时间。

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

【讨论】:

  • 调用 pthread_exit() 没有帮助。而不是程序的正常行为,我通过最后一个线程获得了一系列循环。我的系列是指线程 7:一遍又一遍地循环 0-9。
  • 啊,你有另一个错误。您在第一个线程的堆栈上创建move,但其他线程访问其成员。因此,在所有线程完成之前,您不能允许该堆栈被销毁。
  • 嗯,我在 C++ 标准中找不到pthread_exit。这可能适用于 Unix 系统,但即便如此,C++ 中也没有要求从 main 调用 pthread_exit 会做任何明智的事情。特别是,我敢打赌它不会破坏全局对象。
猜你喜欢
  • 2019-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多