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

Intel TBB run a function in a parallel thread?

本文关键字:运行 函数 线程 并行 TBB 英特尔      更新时间:2023-10-16

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

我想使用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()

英特尔TBB并非用于此类目的。引用教程:

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

使用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();

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