C++程序中启动线程的方法

2020-01-06 13:26:37刘景俊

也可能是:

 

 
  1. Hello from thread Hello from thread Hello from thread 139810974787328Hello from thread 139810983180032Hello from thread  139810966394624 
  2. 139810991572736  139810958001920 

或者其他结果,因为多个线程的执行是交错的。你完全没有办法去控制线程的执行顺序(否则那还要线程干吗?)

当线程要执行的代码就一点点,你没必要专门为之创建一个函数,你可以使用 lambda 来定义要执行的代码,因此第一个例子我们可以改写为:

 

 
  1. #include <thread>  #include <iostream> 
  2. #include <vector>   
  3. int main(){  std::vector<std::thread> threads; 
  4.   for(int i = 0; i < 5; ++i){ 
  5. threads.push_back(std::thread([](){  std::cout << "Hello from thread " << std::this_thread::get_id() << std::endl; 
  6. }));  } 
  7.   for(auto& thread : threads){ 
  8. thread.join();  } 
  9.   return 0;