gpt4 book ai didi

c++ - 多个线程可以加入同一个boost::thread吗?

转载 作者:太空狗 更新时间:2023-10-29 21:38:32 25 4
gpt4 key购买 nike

pthreads如果多个线程尝试加入同一个线程,则具有未定义的行为:

If multiple threads simultaneously try to join with the same thread, the results are undefined.

boost::thread也是如此秒?文档似乎没有具体说明这一点。

如果它未定义,那么多线程等待一个线程完成的干净方法是什么?

最佳答案

If it is undefined, then what would be a clean way for multiple threads to wait on one thread completing?

干净的方法是让一个线程通知其他线程它已完成。一个 packaged_task 包含一个可以等待的 future,这对我们有帮助。

这是一种方法。我使用了 std::thread 和 std::packaged_task,但您也可以使用 boost 等价物。

#include <thread>
#include <mutex>
#include <future>
#include <vector>
#include <iostream>

void emit(const char* msg) {
static std::mutex m;
std::lock_guard<std::mutex> l(m);
std::cout << msg << std::endl;
std::cout.flush();
}

int main()
{
using namespace std;

auto one_task = std::packaged_task<void()>([]{
emit("waiting...");
std::this_thread::sleep_for(std::chrono::microseconds(500));
emit("wait over!");
});

// note: convert future to a shared_future so we can pass it
// to two subordinate threads simultaneously
auto one_done = std::shared_future<void>(one_task.get_future());
auto one = std::thread(std::move(one_task));

std::vector<std::thread> many;
many.emplace_back([one_done] {
one_done.wait();
// do my thing here
emit("starting thread 1");
});

many.emplace_back([one_done] {
one_done.wait();
// do my thing here
emit("starting thread 2");
});

one.join();
for (auto& t : many) {
t.join();
}

cout << "Hello, World" << endl;
return 0;
}

预期输出:

waiting...
wait over!
starting thread 2
starting thread 1
Hello, World

关于c++ - 多个线程可以加入同一个boost::thread吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35214121/

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