代码:
#include <iostream>
#include <thread>void func(int n_print);int main(int argc, char* argv[])
{std::cout << "Thread_ID of main(): " << std::this_thread::get_id() << std::endl;std::thread th1(func, 5);std::thread th2(func, 3);// th1.join();for (int i = 0; i < 5; i++) {std::cout << "main()" << std::endl;}std::cout << "main()" << std::endl;std::cout << "main()" << std::endl;std::cout << "main()" << std::endl;th1.join();th2.join();return 0;
}void func(int n_print)
{for (int i = 0; i < n_print; i++) {std::cout << "Thread_ID: " << std::this_thread::get_id() << " n = "<< n_print << std::endl;std::cout << i << ": " << "from func()" << std::endl;}
}
运行结果:
Thread_ID of main(): 1676
main()
main()
main()
main()
main()
main()
main()
main()
Thread_ID: Thread_ID: 988 n = 3
0: from func()
Thread_ID: 988 n = 3
1: from func()
Thread_ID: 988 n = 3
2: from func()
11220 n = 5
0: from func()
Thread_ID: 11220 n = 5
1: from func()
Thread_ID: 11220 n = 5
2: from func()
Thread_ID: 11220 n = 5
3: from func()
Thread_ID: 11220 n = 5
4: from func()