英特尔TBB在并行线程中运行一个函数?

时间:2012-07-19 14:53:25

标签: c++ multithreading opencv tbb

基本上我正在开发一个opencv应用程序。我在with_tbb中构建了 OpenCV cmake选项。

我想使用intel tbb来运行并行线程,该线程在某些时间间隔更新一些全局变量。类似的东西:

vector<int> mySharedVar;

void secondaryThreadFunction() {
 while(true) {
   Do some operations
   And update mySharedVar if necessarily  

   usleep(1000);
 }
}

int main() {
   run in parallel secondaryThreadFunction;

   in the master Thread keep doing something based on mySharedVar

   while(true) {
    do something;
   }
}

如何在另一个帖子上运行secondaryThreadFunction()

1 个答案:

答案 0 :(得分:3)

英特尔TBB并不适用于此类目的。 引自Tutorial

  

英特尔®线程构建模块旨在提高性能。   大多数通用线程包支持许多不同类型   线程化,例如图形中异步事件的线程化   用户界面。因此,通用包往往是   提供基础的低级工具,而不是解决方案。代替,   英特尔®线程构建模块专注于特定的目标   并行化计算密集型工作,提供更高级别的工作,   更简单的解决方案。

使用boost::thread或C ++ 11线程功能可以轻松实现您想要做的事情:

   // using async
   auto fut = std::async(std::launch::async, secondaryThreadFunction);
   // using threads (for boost, just replace std with boost)
   std::thread async_thread(secondaryThreadFunction);

   in the master Thread keep doing something based on mySharedVar

   while(true) {
    do something;
   }

   // in case of using threads
   async_thread.join();

请记住同步对任何共享变量的访问权限。