一、Windows临界区的基本用法
CRITICAL_SECTION my_winsc; //定义一个Windows的临界区,相当于一个mutex变量
InitializeCriticalSection(&my_winsc); //初始化
EnterCriticalSection(&my_winsc); //进入临界区,相当于lock()
LeaveCriticalSection(&my_winsc); //离开临界区,相当于unlock()
线程thread_1打印1-50,线程thread_2打印51-100
1 #include <iostream> 2 #include <Windows.h> 3 #include <thread> 4 using namespace std; 5 6 int Count = 0; 7 CRITICAL_SECTION my_winsc; //定义一个Windows的临界区,相当于mutex 8 9 void mythead_1() 10 { 11 for (int i = 0; i < 50; i++) 12 { 13 EnterCriticalSection(&my_winsc); //进入临界区,相当于lock() 14 EnterCriticalSection(&my_winsc); //进入临界区,相当于lock() 15 Count++; 16 cout << std::this_thread::get_id() << "线程:" << Count << endl; 17 LeaveCriticalSection(&my_winsc); //离开临界区,相当于unlock() 18 LeaveCriticalSection(&my_winsc); //离开临界区,相当于unlock() 19 } 20 } 21 22 void mythread_2() 23 { 24 for (int i = 0; i < 50; i++) 25 { 26 EnterCriticalSection(&my_winsc); 27 Count++; 28 cout << std::this_thread::get_id() << "线程:" << Count << endl; 29 LeaveCriticalSection(&my_winsc); 30 } 31 } 32 33 34 int main() 35 { 36 37 InitializeCriticalSection(&my_winsc); //初始化 38 thread thread_1(mythead_1); 39 thread thread_2(mythread_2); 40 thread_1.join(); 41 thread_2.join(); 42 43 44 system("pause"); 45 return 0; 46 }
二、Windows临界区与mutex的不同
1.mutex是独立互斥量,临界区是递归的独立互斥量,同一个mutex互斥量在一个线程入口函数只能lock一次,但是在本例中可以多次进入临界区,即可以使用多次加锁,只需对应的解锁相应次数就行了
2.Windows临界区必须初始化