gpt4 book ai didi

c++ - 重用线程 - boost 与标准线程行为

转载 作者:搜寻专家 更新时间:2023-10-31 01:27:20 26 4
gpt4 key购买 nike

我似乎在 boost 和 std 线程之间获得了不同的线程对象分配行为。如果我使用 boost 线程,可以重新分配线程成员变量并重新创建线程。如果我使用标准线程,我会收到运行时错误 terminate called without an active exception .

这是有问题的代码(运行,然后用 boost::替换 std::)

class ThreadTest 
{
private:
std::thread mythread;
std::atomic<bool> running_;

int doSomeWork(){
int i=0;
cout << "starting" << endl;
while(running_){
cout << "working" << endl;
std::this_thread::sleep_for (std::chrono::seconds(1));
if (i>3){ break; } else { i++; }
}
running_ = false;
}

public:
void runThread(){
running_ = true;
mythread = std::thread(&ThreadTest::doSomeWork, this);
}

void joinThread(){
mythread.join();
}
};

int main(){
ThreadTest test;
test.runThread();
std::this_thread::sleep_for (std::chrono::seconds(10));
test.runThread();
test.joinThread();
return 0;
}

boost 输出:

starting
working
working
working
working
working
starting
working
working
working
working
working

std::的输出

starting
working
working
working
working
working
terminate called without an active exception
Aborted (core dumped)

这段特殊的代码在一个库中使用,该库似乎没有 boost 作为依赖项。我想保持这种状态,那么有没有一种方法可以使用标准线程来获得 boost “重新分配”行为?

编辑 - 解决方案

我添加了一个 std::atomic<bool> threadInitialized_;到设置为 true 的类在线程函数中 doSomeWork() .我的runThread()方法变为:

void runThread(){
if(threadInitialized_)
mythread.join();

running_ = true;
mythread = std::thread(&ThreadTest::doSomeWork, this);
}

我知道这会阻塞主线程,直到生成的线程完成。

最佳答案

通常,正如上面正确指出的那样,所有(可连接的)线程都需要在它们的对象被销毁之前连接或分离。

现在,boost 线程和 std::thread 之间的(许多)区别之一是 Boost 线程在它们的析构函数中分离它们自己,而 std::thread 不会;因此,您对 std::thread 的错误使用会正确触发 terminate()。

PS:不要(!!)相信上面的其他评论者认为 std::threads 和 boost::thread 的行为应该“相同”——这不是真的!

关于c++ - 重用线程 - boost 与标准线程行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53531790/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com