如何让C ++ 11线程运行几种不同的功能?

All*_*nzi 5 c++ multithreading c++11

我正在学习C ++ 11中的新多线程技术。我在网络上阅读的几乎所有教程都在教如何启动执行一个函数的新线程(一个或多个线程),如何稍后加入(或分离)一个或多个线程以及如何使用mutex等避免竞争状况。

但是我没有看到它们显示如何使线程在程序的不同部分执行多个功能。问题是,使用C ++ 11线程是否可以实现以下目标?如果是这样,怎么办?(举个例子会很棒)。

void func1(std::vector<int> & data1){ ... }

void func2(std::vector<int> & data2){ ... }

//  main function version I
int main(){
   std::vector<int> data1; 
   // prepare data1 for func1;
   std::thread t1(func1, std::ref(data1));

   std::vector<int> data2; 
   // prepare data2 for func2;
   if (func1 in t1 is done){ 
         t1(func2, std::ref(data2)); 
   }

   t1.join();
   return 0;      
}
Run Code Online (Sandbox Code Playgroud)

此外,如果我想将上述main函数体放入循环中,如下所示。可能吗?如果是这样,怎么办?

//main function version II
int main(){
   std::vector<int> bigdata1;
   std::vector<int> bigdata2;

   std::thread t1; // Can I do this without telling t1 the function 
                   // to be executed?

   for(int i=0; i<10; ++i){
       // main thread prepare small chunk smalldata1 from bigdata1 for func1;

       if(t1 is ready to execute a function){t1(func1, std::ref(smalldata1));}

       // main thread do other stuff, and prepare small chunk smalldata2 from bigdata2 for func2;

       if (func1 in t1 is done){ 
            t1(func2, std::ref(smalldata2)); 
       }
   }

   t1.join();
   return 0;      
}
Run Code Online (Sandbox Code Playgroud)

Yuc*_*ong 2

参考cplusplus.com

默认构造函数构造一个不代表任何执行线程的线程对象。

因此std::thread t根本没有定义可执行线程。线程函数必须在创建线程时提供,并且不能在创建后设置。

对于您的 main 函数版本 I,您必须创建两个线程。如下:

int main(){
    std::vector<int> data1; 
    // prepare data1 for func1;
    std::thread t1(func1, std::ref(data1));

    std::vector<int> data2; 
    // prepare data2 for func2;
    t1.join(); // this is how you wait till func1 is done

    // you will have to create a new thread here for func2
    std::thread t2(func2, std::ref(data2)); 
    t2.join(); // wait for thread2 (func2) to end

    return 0;      
}
Run Code Online (Sandbox Code Playgroud)

同样,您可以将它们放入一个循环中,这将给您main 函数版本 II