-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathtry_lock_until_success.cpp
More file actions
56 lines (48 loc) · 1.37 KB
/
try_lock_until_success.cpp
File metadata and controls
56 lines (48 loc) · 1.37 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
/*
* A simple example with 30 timed mutexes where one is locked
* for 40 milliseconds before being released.
*/
#include <beman/timed_lock_alg/mutex.hpp>
#include <chrono>
#include <functional>
#include <iostream>
#include <mutex>
#include <thread>
#include <utility>
namespace {
// joining thread for implementations missing std::jthread
class JThread : public std::thread {
public:
template <class... Args>
JThread(Args&&... args) : std::thread(std::forward<Args>(args)...) {}
~JThread() {
if (joinable()) {
join();
}
}
};
} // namespace
using namespace std::chrono_literals;
namespace tla = beman::timed_lock_alg;
void foo(std::timed_mutex& m0, std::timed_mutex& m1) {
std::lock(m0, m1);
std::cout << "locked\n";
std::this_thread::sleep_for(200ms);
m0.unlock();
std::cout << "0 unlocked\n";
std::this_thread::sleep_for(100ms);
m1.unlock();
std::cout << "1 unlocked\n";
}
int main() {
const char* name[]{"foo", "bar"};
const char* act[]{"ping", "pong"};
std::timed_mutex m0, m1;
JThread th(foo, std::ref(m0), std::ref(m1));
std::this_thread::sleep_for(100ms);
std::cout << "trying\n";
for (int rv; (rv = tla::try_lock_for(20ms, m0, m1)) != -1;) {
std::cout << "failed on " << name[rv] << ", taking action " << act[rv] << '\n';
}
std::cout << "success\n";
}