C++多线程chap2多线程通信和同步3

这里,只是记录自己的学习笔记。

顺便和大家分享多线程的基础知识。然后从入门到实战。有代码。

知识点来源:

https://edu.51cto.com/course/26869.html


2 利用栈特性自动释放锁 RAII
2.1 什么是RAII,手动代码实现
RAII(Resource Acquisition Is Initialization)c++之父Bjarne Stroustrup提出;
使用局部对象来管理资源的技术称为资源获取即初始化;它的生命周期是由操作系统来管理的,
无需人工介入; 资源的销毁容易忘记,造成死锁或内存泄漏。


手动实现RAII管理mutex资源

 1 #include <thread>
 2 #include <iostream>
 3 #include <string>
 4 #include <mutex>
 5 #include <shared_mutex>
 6 
 7 using namespace std;
 8 
 9 // RAII
10 class XMutex {
11 public:
12     XMutex(mutex& mux):mux_(mux){
13 
14         cout << "Lock" << endl;
15         mux.lock();
16     }
17 
18     ~XMutex() {
19         cout << "Unlock" << endl;
20         mux_.unlock();
21     }
22 
23 private:
24     mutex& mux_;
25 };
26 
27 static mutex mux;
28 void TestMutex(int status) {
29     XMutex lock(mux);
30 
31     if (status == 1) {
32         cout << "=1" << endl;
33         return;
34     }
35     else {
36         cout << "!=1" << endl;
37         return;
38     }
39 }
40 
41 int main() {
42 
43     TestMutex(1);
44     TestMutex(2);
45 
46 
47     getchar();
48     return 0;
49 }

 

 

作者:小乌龟
【转载请注明出处,欢迎转载】 希望这篇文章能帮到你

 

原文地址:https://www.cnblogs.com/music-liang/p/15589495.html