-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMutexTryLock.cpp
More file actions
51 lines (41 loc) · 1.43 KB
/
MutexTryLock.cpp
File metadata and controls
51 lines (41 loc) · 1.43 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
/* TOPIC: std::mutex::try_lock() On Mutex In C++11 Threading
0. try_lock() Tries to lock the mutex. Returns immediately. On successful lock acquisition returns true otherwise returns false.
1. If try_lock() is not able to lock mutex, then it doesn't get blocked that's why it is called non-blocking.
2. If try_lock is called again by the same thread which owns the mutex, the behavior is undefined.
It is a dead lock situation with undefined behavior. (if you want to be able to lock the same mutex by same thread more than one time the go for recursive_mutex)
There are so many try_lock function
1. std::try_lock
2. std::mutex::try_lock
3. std::shared_lock::try_lock
4. std::timed_mutex::try_lock
5. std::unique_lock::try_lock
6. std::shared_mutex::try_lock
7. std::recursive_mutex::try_lock
8. std::shared_timed_mutex::try_lock
9. std::recursive_timed_mutex::try_lock */
#include<iostream>
#include<mutex>
#include<thread>
using namespace std;
int counter = 0;
std::mutex mx;
void IncreaseCounter100000Times()
{
for (int i = 0; i < 100000; i++)
{
if(mx.try_lock())
++counter;
mx.unlock();
}
}
int main()
{
std::thread t1(IncreaseCounter100000Times);
std::thread t2(IncreaseCounter100000Times);
t1.join();
t2.join();
cout<<"Counter could increase up to : "<<counter<<endl;
return 0;
}
//compile: g++ -std=c++11 MutexTryLock.cpp -pthread
//Output: Counter could increase up to : 170463