如果多个线程尝试加入同一个线程,则 pthreads
具有未定义的行为:
boost::thread
也是如此吗?该文档似乎没有指定这一点。
如果未定义,那么多线程等待一个线程完成的干净方法是什么?
最佳答案
干净的方法是让一个线程通知其他线程它已完成。一个 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/