C++多线程基础学习笔记(十)
程序员文章站
2024-02-07 09:47:58
一、Windows临界区的基本用法 CRITICAL_SECTION my_winsc; //定义一个Windows的临界区,相当于一个mutex变量 InitializeCriticalSection(&my_winsc); //初始化 EnterCriticalSection(&my_winsc ......
一、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临界区必须初始化