我是 C++11 线程的新手,我想知道如何管理工作线程(使用标准库)来执行一些任务然后消失。我有一个线程池 vector<thread *> thread_pool
维护事件线程列表。
假设我启动了一个新线程并使用 thread_pool.push_back(new thread(worker_task))
将其添加到池中。 ,其中 worker_task
定义如下:
void worker_task()
{
this_thread::sleep_for(chrono::milliseconds(1000));
cout << "Hello, world!\n"
}
一旦工作线程终止,从池中可靠地删除线程的最佳方法是什么?主线程需要持续运行,不能阻塞在
join
称呼。我对代码的一般结构比同步的复杂性更困惑。编辑:看起来我在代码中误用了池的概念。我的意思是我有一个当前正在运行的线程列表。
最佳答案
您可以使用 std::thread::detach “将执行线程与线程对象分开,允许执行独立继续。一旦线程退出,任何分配的资源都将被释放。”
如果每个线程都应该使其状态可见,您可以将此功能移到线程函数中。
std::mutex mutex;
using strings = std::list<std::string>;
strings info;
strings::iterator insert(std::string value) {
std::unique_lock<std::mutex> lock{mutex};
return info.insert(info.end(), std::move(value));
}
auto erase(strings::iterator p) {
std::unique_lock<std::mutex> lock{mutex};
info.erase(p);
}
template <typename F>
void async(F f) {
std::thread{[f] {
auto p = insert("...");
try {
f();
} catch (...) {
erase(p);
throw;
}
erase(p);
}}.detach();
}
关于multithreading - C++11 - 管理工作线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24516928/