多线程初级
1 #include <iostream> 2 #include <thread> 3 #include <windows.h> 4 #include <mutex> 5 6 //两个线程并行访问一个变量 7 8 int g_num = 20;//找到或者找不到的标识 9 std::mutex g_mutex; 10 11 void goA(int num) 12 { 13 g_mutex.lock();//你访问的变量,在你访问期间,别人访问不了 14 15 for (int i = 0; i < 15; i++) 16 { 17 Sleep(300); 18 g_num = 10;//修改全局变量 19 std::cout << "线程" << num << " " << g_num << std::endl; 20 } 21 22 g_mutex.unlock();//解锁 23 } 24 25 void goB(int num) 26 { 27 for (int i = 0; i < 15; i++) 28 { 29 Sleep(500); 30 g_num = 11;//修改全局变量 31 std::cout << "线程" << num << " " << g_num << std::endl; 32 } 33 } 34 35 void main() 36 { 37 std::thread t1(goA, 1); 38 std::thread t2(goB, 2); 39 t1.join(); 40 t2.join(); 41 42 std::cin.get(); 43 }