-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmemory_leak.cpp
85 lines (77 loc) · 2.14 KB
/
memory_leak.cpp
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include "etcd/Client.hpp"
#include <future>
class DistributedLock {
public:
DistributedLock(const std::string &lock_name,
uint timeout = 0);
~DistributedLock() noexcept;
inline bool lock_acquired() {
return _acquired;
}
private:
bool _acquired = false;
std::string _lock_key;
std::unique_ptr<::etcd::Client> _etcd_client;
};
DistributedLock::DistributedLock(const std::string &lock_name,
uint timeout) {
_etcd_client = std::make_unique<etcd::Client>("localhost:12379");
try {
if (timeout == 0) {
etcd::Response resp = _etcd_client->lock(lock_name).get();
if (resp.is_ok()) {
_lock_key = resp.lock_key();
_acquired = true;
}
} else {
std::future<etcd::Response> future = std::async(std::launch::async, [&]() {
etcd::Response resp = _etcd_client->lock(lock_name).get();
return resp;
});
std::future_status status = future.wait_for(std::chrono::seconds(timeout));
if (status == std::future_status::ready) {
auto resp = future.get();
if (resp.is_ok()) {
_lock_key = resp.lock_key();
_acquired = true;
}
} else if (status == std::future_status::timeout) {
std::cout << "failed to acquire distributed because of lock timeout" << std::endl;
} else {
std::cout << "failed to acquire distributed lock" << std::endl;
}
}
} catch (std::exception &e) {
throw e;
}
}
DistributedLock::~DistributedLock() noexcept {
if (!_acquired) {
return;
}
try {
auto resp = _etcd_client->unlock(_lock_key).get();
if (!resp.is_ok()) {
std::cout << resp.error_code() << std::endl;
}
} catch (std::exception &e) {
throw e;
}
}
int main() {
int i = 0;
while(true) {
{
DistributedLock lock(std::to_string(i), 3);
if(!lock.lock_acquired()) {
std::cout << "failed to acquire lock" << std::endl;
}
std::this_thread::sleep_for(std::chrono::milliseconds (10));
}
++i;
if (i == 10) {
i = 0;
}
std::this_thread::sleep_for(std::chrono::seconds(3));
}
}