-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstd_try_lock.cpp
More file actions
60 lines (51 loc) · 1.45 KB
/
Copy pathstd_try_lock.cpp
File metadata and controls
60 lines (51 loc) · 1.45 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
//TOPIC: try_lock() in C++11 Threading
// 1. std::try_lock() tries to lock all lockable objects passed in it one by one in given order.
// SYNTAX: std::try_lock(m1,m2,m3,m4,...,mn);
// 2.On success this function returns -1 otherwise it will return 0-based mutex index number which it could not lock.
// 3. If it fails to lock any of the mutex then it will release all the mutex it locked before.size
// 4. If a call to try_lock results in an exception , unlock is called for any locked objects before rethrowing.
#include <mutex>
#include <thread>
#include <iostream>
#include <chrono>
using namespace std;
int X=0, Y=0;
std::mutex m1, m2;
void doSomeWorkForSeconds(int seconds) { std::this_thread::sleep_for(std::chrono::seconds(seconds)); }
void incrementXY(int& XorY, std::mutex& m, const char* desc) {
for(int i=0; i<5; ++i){
m.lock();
++XorY;
cout << desc << XorY << '\n';
m.unlock();
doSomeWorkForSeconds(1);
}
}
void consumeXY () {
int useCount = 5;
int XplusY = 0;
while(1){
int lockResult = std::try_lock(m1,m2);
if(lockResult == -1){
if(X!=0 && Y!=0){
--useCount;
XplusY+=X+Y;
X = 0;
Y = 0;
cout << "XplusY " << XplusY << '\n';
}
m1.unlock();
m2.unlock();
if(useCount == 0) break;
}
}
}
int main() {
std::thread t1(incrementXY, std::ref(X), std::ref(m1), "X ");
std::thread t2(incrementXY, std::ref(Y), std::ref(m2), "Y ");
std::thread t3(consumeXY);
t1.join();
t2.join();
t3.join();
return 0;
}