线程同步是指同一进程中的多个线程互相协调工作从而达到一致性。之所以需要线程同步,是因为多个线程同时对一个数据对象进行修改操作时,可能会对数据造成破坏,下面是多个线程同时修改同一数据造成破坏的例子:
1 #include <thread> 2 #include <iostream> 3 4 void Fun_1(unsigned int &counter); 5 void Fun_2(unsigned int &counter); 6 7 int main() 8 { 9 unsigned int counter = 0; 10 std::thread thrd_1(Fun_1, counter); 11 std::thread thrd_2(Fun_2, counter); 12 thrd_1.join(); 13 thrd_2.join(); 14 system("pause"); 15 return 0; 16 } 17 18 void Fun_1(unsigned int &counter) 19 { 20 while (true