-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathtrylock.cpp
More file actions
37 lines (30 loc) · 687 Bytes
/
Copy pathtrylock.cpp
File metadata and controls
37 lines (30 loc) · 687 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
#include <iostream>
#include <chrono>
#include <thread>
#include <mutex>
std::mutex g_lock;
void job1(){
g_lock.lock();
std::cout << "job1 is executed" << std::endl;
g_lock.unlock();
}
void job2(){
if(g_lock.try_lock()){
std::cout << "job2 is executed" << std::endl;
g_lock.unlock();
}else{
using namespace std::chrono_literals;
std::this_thread::sleep_for(5s);
if(g_lock.try_lock()){
std::cout << "job2 exected on 2nd try\n";
g_lock.unlock();
}
}
}
int main(){
std::thread thread1(job1);
std::thread thread2(job2);
thread1.join();
thread2.join();
return 0;
}