/**
* 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;
}