-
Notifications
You must be signed in to change notification settings - Fork 2
/
std_lock.cpp
46 lines (43 loc) · 1 KB
/
std_lock.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <list>
#include <iostream>
#include <mutex>
#include <algorithm>
#include <thread>
#include <unistd.h>
using namespace std;
class data_protect;
void swap(data_protect& , data_protect& );
//是线程安全的
class data_protect{
friend void swap(data_protect& , data_protect& );
private:
list<int> alist{1,2};
mutex m;
public:
void add_list(int val){
//操作双向链表时,加锁了
lock_guard<mutex> g(m);
alist.push_back(val);
}
bool contains(int val){
//操作双向链表时,加锁了
lock_guard<mutex> g(m);
return find(alist.begin(), alist.end(), val) != alist.end();
}
};
void swap(data_protect& d1, data_protect& d2){
//if(d1 == d2) return;
std::lock(d1.m, d2.m);
//造成死锁
//d1.add_list(11);
lock_guard<mutex> lock_a(d1.m, std::adopt_lock);
lock_guard<mutex> lock_b(d2.m, std::adopt_lock);
swap(d1.alist, d2.alist);
//没有unlock成员函数
//lock_a.unlock();
}
int main(){
data_protect d1, d2;
swap(d1, d2);
d1.add_list(11);
}