forked from landbroken/BasicKnowledge
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3_mutex.cpp
More file actions
48 lines (40 loc) · 953 Bytes
/
3_mutex.cpp
File metadata and controls
48 lines (40 loc) · 953 Bytes
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
47
48
#include "stdafx.h"
static std::mutex g_lock;
/*
你在lock一个 std::mutex 对象之后必须解锁(unlock)。
如果你已经对其加锁,你不能再次lock。
*/
void lock_unlock()
{
//上锁
g_lock.lock();
cout << "in id: " << this_thread::get_id() << endl;
this_thread::sleep_for(chrono::seconds(1));
cout << "out id: " << this_thread::get_id() << endl;
//解锁
g_lock.unlock();
}
void f_lock_guard()
{
//lock_guard在构造时会自动锁定互斥量,而在退出作用域后进行析构时就会自动解锁.
lock_guard<std::mutex> lock(g_lock);
cout << "in id: " << this_thread::get_id() << endl;
this_thread::sleep_for(chrono::seconds(1));
cout << "out id: " << this_thread::get_id() << endl;
}
int mutex_demo()
{
std::thread t1(lock_unlock);
std::thread t2(lock_unlock);
std::thread t3(lock_unlock);
t1.join();
t2.join();
t3.join();
std::thread t4(f_lock_guard);
std::thread t5(f_lock_guard);
std::thread t6(f_lock_guard);
t4.join();
t5.join();
t6.join();
return 0;
}