线程同步问题和lock_guard上锁模板
lock_guard是一个c++提供的类模板可以用来进行线程对临界区资源的互斥访问从而达到线程同步的问题
#include<iostream> using namespace std; #include<thread> #include<stdlib.h> #include<mutex> #include<windows.h> unsigned int counter = 0; mutex mtx; void fun1() { while (true) { lock_guard<mutex>mtx_lock(mtx); ++counter; if (counter > 1000) { break; } else { cout << "线程1 是: " << counter << endl; } } } void fun2() { while (true) { lock_guard<mutex>mtx_lock(mtx);//lock_guard的类模板用来进行加锁解锁 ++counter; if (counter > 1000) { break; } else { cout << "线程2 是: " << counter << endl; } } } void main() { CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)fun1, NULL, 0, NULL);//标准教科书式写法,但是很蠢 thread mythread1(fun1); thread mythread2(fun2); mythread1.join(); mythread2.join(); system("pause"); }