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
/**
 * Simplistic deadlock demo
 */

#include <stdio.h>
#include <pthread.h>

#include <unistd.h>

#include <assert.h>

pthread_mutex_t lock1;
pthread_mutex_t lock2;

void *thread1(void *args) {

  // acquire lock1, then lock2
  pthread_mutex_lock(&lock1);
  sleep(1); // "some work"
  pthread_mutex_lock(&lock2);

  printf("Working hard in thread1\n");

  pthread_mutex_unlock(&lock1);
  pthread_mutex_unlock(&lock2);

  return NULL;
}

void *thread2(void *args) {
  // note how the locks are acquired in reverse order from thread1
  pthread_mutex_lock(&lock2);
  sleep(1); // "some work"
  pthread_mutex_lock(&lock1);

  printf("Working hard in thread2\n");

  pthread_mutex_unlock(&lock1);
  pthread_mutex_unlock(&lock2);

  return NULL;
}

int main(int argc, char **argv) {

    pthread_t th[2];

    // initialize locks
    pthread_mutex_init(&lock1, NULL);
    pthread_mutex_init(&lock2, NULL);

    // start threads
    pthread_create(&th[0], NULL, thread1, NULL);
    pthread_create(&th[1], NULL, thread2, NULL);

    // wait for threads
    pthread_join(th[0], NULL);
    pthread_join(th[1], NULL);
    return 0;
}