代码之家  ›  专栏  ›  技术社区  ›  ssb

线程构建块:死锁,因为所有线程都用完了

  •  6
  • ssb  · 技术社区  · 11 年前

    在Intel线程构建块框架中,如何确保所有线程不忙于等待其他线程完成。

    例如,考虑以下代码,

    #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;
    }
    

    这里是 main 当TBB库使用的线程池中有线程时,函数会作为任务生成。然后,当第二次调用生成更多任务时 run_something 函数时,TBB调度器会发现没有线程可用,只是死锁。也就是说,我看到打印语句在4个超线程的机器上精确地执行了4次,在8个超线程机器上精确执行了8次。

    我如何避免这种情况,特别是,有没有办法确保 task_group 或 task_arena 或 parallel_for 构造使用两个完全不相交的线程集?

    1 回复  |  直到 11 年前
        1
  •  4
  •   Anton    11 年前

    这个 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() 如中所述 the reference 对于析构函数: Requires: Method wait must be called before destroying a task_group, otherwise the destructor throws an exception.

    至于共享线程池。是的,TBB有一个共享线程池。但您可以使用 task_arena 没有任务可以离开竞技场,但工作线程可以在运行任务之间的时间内跨竞技场迁移。

    推荐文章