c++ - 如何让一个 C++11 线程运行多个不同的函数?

标签 c++ multithreading c++11

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

但我没有看到其中任何一个显示如何让一个线程在程序的不同部分执行多个函数。问题是,使用 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;      
}

此外,如果我想将上面的 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;      
}

最佳答案

引用自cplusplus.com :

default constructor constructs a thread object that does not represent any thread of execution.

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

对于您的主要功能版本 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;      
}

同样,您可以将它们放在一个循环中,这样就可以得到主函数版本 II

关于c++ - 如何让一个 C++11 线程运行多个不同的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30180008/

相关文章:

c# - BlockingCollection.TakeFromAny 方法是否适合构建阻塞优先级队列?

c++ - 错误是 xmemory - 缺少 c++0x 支持?

c++ - 错误 C2065 : 'errno' : undeclared identifier in <string> in Visual Studio 2012

c++ - 允许左值引用和禁止右值引用作为函数参数?

c++ - 在线程之间共享一个文件描述符

c++ - 为 C++ 源文件构建 debian 包时出错

multithreading - 线程因锁定的互斥锁而崩溃

ios - UIFont线程安全吗?

c++ - 如何覆盖 std::atomic 类的默认析构函数

c++ - 多个析构函数调用