Created
December 12, 2020 18:05
-
-
Save rouxcaesar/9b16d37789decddcab65dec6916264f2 to your computer and use it in GitHub Desktop.
Deadlock example with C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <pthread.h> | |
pthread_mutex_t lock1, lock2; | |
void *resource1(){ | |
pthread_mutex_lock(&lock1); | |
printf("Job started in resource1..\n"); | |
sleep(2); | |
printf("Trying to get resource2\n"); | |
pthread_mutex_lock(&lock2); | |
printf("Aquired resource2\n"); | |
pthread_mutex_unlock(&lock2); | |
printf("Job finished in resource1..\n"); | |
pthread_mutex_unlock(&lock1); | |
pthread_exit(NULL); | |
} | |
void *resource2(){ | |
pthread_mutex_lock(&lock2); | |
printf("Job started in resource2..\n"); | |
sleep(2); | |
printf("Trying to get resource1\n"); | |
pthread_mutex_lock(&lock1); | |
printf("Aquired resource1\n"); | |
pthread_mutex_unlock(&lock1); | |
printf("Job finished in resource2..\n"); | |
pthread_mutex_unlock(&lock2); | |
pthread_exit(NULL); | |
} | |
int main() { | |
pthread_mutex_init(&lock1,NULL); | |
pthread_mutex_init(&lock2,NULL); | |
pthread_t t1,t2; | |
pthread_create(&t1,NULL,resource1,NULL); | |
pthread_create(&t2,NULL,resource2,NULL); | |
pthread_join(t1,NULL); | |
pthread_join(t2,NULL); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment