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

2020-01-06 13:26:37刘景俊
  • #include <thread>  #include <iostream> 
  • #include <vector>   
  • void hello(){  std::cout << "Hello from thread " << std::this_thread::get_id() << std::endl; 
  • }   
  • int main(){  std::vector<std::thread> threads; 
  •   for(int i = 0; i < 5; ++i){ 
  • threads.push_back(std::thread(hello));  } 
  •   for(auto& thread : threads){ 
  • thread.join();  } 
  •   return 0; 
  • 依次启动每个线程,然后把它们保存到一个 vector 容器中,程序执行结果是不可预测的,例如:

     

     
    1. Hello from thread 140276650997504  Hello from thread 140276667782912 
    2. Hello from thread 140276659390208  Hello from thread 140276642604800 
    3. Hello from thread 140276676175616