我正在学习 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/