-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1b-deadlock.cpp
More file actions
50 lines (43 loc) · 1.24 KB
/
1b-deadlock.cpp
File metadata and controls
50 lines (43 loc) · 1.24 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
#include <mutex>
#include <condition_variable>
#include <thread>
#include <vector>
#include <iostream>
template<int Remainder, int Factor>
void
incrementer(int &counter, int till, std::mutex &lock, std::condition_variable ¬ify)
{
std::unique_lock<std::mutex> lk(lock, std::defer_lock);
for (;;) {
lock.lock();
while (counter < till && counter % Factor != Remainder)
notify.wait(lk);
if (counter >= till)
break;
int next = ++counter;
lock.unlock();
notify.notify_one();
if (next >= till)
break;
}
}
int main(int argc, char **argv)
{
if (argc != 2 || std::string_view(argv[1]) == "--help") {
std::cout << "Usage: " << argv[0] << " increment-till-this-value"
<< " ... and expect a deadlock!" << std::endl;
return 1;
}
int count = 0, till = std::atoi(argv[1]);
std::mutex lock;
std::condition_variable notify;
std::vector<std::thread> workers;
workers.reserve(3);
workers.emplace_back([&]() { incrementer<0, 2>(count, till, lock, notify); });
workers.emplace_back([&]() { incrementer<1, 2>(count, till, lock, notify); });
workers.emplace_back([&]() { incrementer<1, 2>(count, till, lock, notify); });
for (auto &t : workers)
t.join();
std::cout << "New counter value is " << count << std::endl;
return 0;
}