#include<iostream> #include<thread> #include<mutex> #include<atomic> using namespace std; mutex g_mutex; atomic<bool> isok = false; void func(int id) { //只有当所有线程创建完成之后才能启动,否则会被挂起,让出cpu的控制权给其它等待的线程使用 while (isok == false) { this_thread::yield(); } for (int i = 0; i < 5; i++) { lock_guard<mutex> lock(g_mutex); cout << "thread id=" << id << " " << i << endl; } } int main() { thread threads[5]; for (int i = 0; i < 5; i++) { threads[i] = thread(func, i); } isok = true; for (int i = 0; i < 5; i++) { threads[i].join(); } system("pause"); return 0; }