Skip to content

Commit 6c9c9d6

Browse files
committed
☠️ Using an additional thread for deadlock detection.
1 parent 10096a0 commit 6c9c9d6

File tree

1 file changed

+31
-1
lines changed

1 file changed

+31
-1
lines changed

cpp/deadlock.cpp

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,15 @@
11
/// Copyright (c) RenChu Wang - All Rights Reserved
22

33
#include <cassert>
4+
#include <chrono>
5+
#include <cstdlib>
6+
#include <exception>
47
#include <iostream>
58
#include <memory>
69
#include <numeric>
710
#include <semaphore>
811
#include <sstream>
12+
#include <thread>
913
#include <vector>
1014

1115
using namespace std;
@@ -33,7 +37,7 @@ class compute : enable_shared_from_this<compute> {
3337

3438
class scoped_semaphore {
3539
public:
36-
scoped_semaphore(counting_semaphore<>& sem, string by)
40+
scoped_semaphore(counting_semaphore<>& sem, const string& by)
3741
: sem_(sem), by_(by) {
3842
cout << "acq(" << by_ << ")\n";
3943
sem_.acquire();
@@ -223,6 +227,31 @@ class lazy_summation : public summation, sema {
223227
}
224228
};
225229

230+
void raise_error_on_deadlock(counting_semaphore<>& sem) {
231+
for (;;) {
232+
if (!sem.try_acquire()) {
233+
cout << "--- deadlock! ---\n";
234+
abort();
235+
}
236+
237+
// Lock is acquired.
238+
cout << "Acquired in deadlock detection. No deadlock\n";
239+
sem.release();
240+
this_thread::sleep_for(chrono::seconds(3));
241+
}
242+
}
243+
244+
class scoped_deadlock_detection {
245+
public:
246+
scoped_deadlock_detection(counting_semaphore<>& sem)
247+
: sem_(sem), th_(thread(raise_error_on_deadlock, ref(sem))) {}
248+
249+
~scoped_deadlock_detection() { th_.join(); }
250+
251+
private:
252+
counting_semaphore<>& sem_;
253+
thread th_;
254+
};
226255
int main() {
227256
using expr = shared_ptr<compute>;
228257
expr one, two, three, sum_six, prod_six, twelve, thrity_six;
@@ -264,6 +293,7 @@ int main() {
264293
}
265294

266295
counting_semaphore<> sem(1);
296+
scoped_deadlock_detection sdd(sem);
267297
{
268298
one = make_shared<lazy_literal>(1, sem);
269299
two = make_shared<lazy_literal>(2, sem);

0 commit comments

Comments
 (0)