voidthfunc(int n){ while (!ready) { this_thread::yield(); //当ready为false时,让出CPU时间片 } for (volatileint i = 0; i < 1000000;++i) {} //执行一些耗时的操作,volatile的意思是避免编译器对这段代码进行优化,确保每次都从内存中读取变量的值 cout << n << ","; }
intmain(){ thread threads[10]; //定义10个线程对象 cout << "10个线程赛跑排名(线程id):" << endl; for (int i = 0; i < 10; i++) { threads[i] = thread(thfunc, i); //启动线程并分配id } ready = true; for (auto& th : threads) th.join(); //等待所有线程执行完毕 cout << endl; return0; }