-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtryLock.cpp
More file actions
44 lines (37 loc) · 719 Bytes
/
tryLock.cpp
File metadata and controls
44 lines (37 loc) · 719 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
#include <iostream>
#include <chrono>
#include <thread>
#include <mutex>
std::mutex gLock;
void job1()
{
gLock.lock();
std::cout << "job1 is running" << std::endl;
gLock.unlock();
}
void job2()
{
if (gLock.try_lock())
{
std::cout << "job2 is running" << std::endl;
gLock.unlock();
}
else
{
using namespace std::chrono_literals;
std::this_thread::sleep_for(1s);
if (gLock.try_lock())
{
std::cout << "job2 is running on second try" << std::endl;
gLock.unlock();
}
}
}
int main()
{
std::thread thread1(job1);
std::thread thread2(job2);
thread1.join();
thread2.join();
return 0;
}