ssb*_*ssb 6 c++ multithreading deadlock tbb c++11
在英特尔线程构建块框架中,如何确保所有线程不忙于等待其他线程完成。
例如考虑以下代码,
#include <tbb/tbb.h>
#include <vector>
#include <cstdlib>
#include <future>
#include <iostream>
std::future<bool> run_something(std::function<bool(bool)> func, bool b) {
auto task = std::make_shared<std::packaged_task<bool()> >(std::bind(func, b));
std::future<bool> res = task->get_future();
tbb::task_group g;
g.run([task]() { (*task)(); });
return res;
};
int main() {
tbb::parallel_for(0, 100, 1, [=](size_t i) {
g.run([] () {
std::cout << "A" << std::endl;
run_something([] (bool b) { return b; }, true).get();
});
});
return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)
这里main函数作为任务产生,因为 TBB 库使用的线程池中有线程。然后,当run_something函数中第二次调用产生更多任务时,TBB 调度程序发现没有可用的线程并且只是死锁。也就是说,我看到该打印语句在 4 超线程机器上执行了 4 次,在 8 超线程机器上执行了 8 次。
我如何避免这种情况,特别是有没有办法确保两个task_grouportask_arena或parallel_for构造使用两个完全不相交的线程集?
std::future与 TBB 的可选并行范例不兼容。确实std::future::get()应该命名为let_me_block_in_system_wait_here(). 除非您希望 TBB 死锁,否则禁止在 TBB 任务之间实现 TBB 任务调度程序不知道的任何类型的同步。也就是说,使用 TBB 方式表达 TBB 任务之间的依赖关系。
可选的并行性意味着您的代码必须仅使用单个线程正确运行。除了主线程之外,只tbb::task::enqueue()承诺至少有一个工作线程。
您的代码甚至不应该编译,因为您g.run()在main()没有声明的情况下使用了g。并且禁止task_group在调用之前销毁wait(),如析构函数参考中所述:Requires: Method wait must be called before destroying a task_group, otherwise the destructor throws an exception.
至于共享线程池。是的,TBB 有一个共享线程池。但您可以使用 来控制工作的共享方式task_arena。任何任务都不能离开 arena,但工作线程可以在运行任务之间的时间内跨 arena 迁移。
| 归档时间: |
|
| 查看次数: |
733 次 |
| 最近记录: |