也可能是:
- Hello from thread Hello from thread Hello from thread 139810974787328Hello from thread 139810983180032Hello from thread 139810966394624
- 139810991572736 139810958001920
或者其他结果,因为多个线程的执行是交错的。你完全没有办法去控制线程的执行顺序(否则那还要线程干吗?)
当线程要执行的代码就一点点,你没必要专门为之创建一个函数,你可以使用 lambda 来定义要执行的代码,因此第一个例子我们可以改写为:
- #include <thread> #include <iostream>
- #include <vector>
- int main(){ std::vector<std::thread> threads;
- for(int i = 0; i < 5; ++i){
- threads.push_back(std::thread([](){ std::cout << "Hello from thread " << std::this_thread::get_id() << std::endl;
- })); }
- for(auto& thread : threads){
- thread.join(); }
- return 0;
- }










