deadlock example
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 <pthread/pthread.h> | |
void* someprocess(void* arg); | |
void *anotherprocess(void* arg); | |
pthread_mutex_t lock; | |
pthread_t tid[2]; | |
int counter; | |
int main(int argc, const char * argv[]) { | |
if (pthread_mutex_init(&lock, NULL) != 0) { | |
printf("\n mutex init has failed\n"); | |
return 1; | |
} | |
// insert code here... | |
pthread_create(&(tid[0]), | |
NULL, | |
&someprocess, NULL); | |
pthread_create(&(tid[1]), | |
NULL, | |
&someprocess, NULL); | |
pthread_join(tid[1], NULL); | |
pthread_join(tid[0], NULL); | |
pthread_mutex_destroy(&lock); | |
return 0; | |
} | |
void *someprocess(void* arg){ | |
pthread_mutex_lock(&lock); | |
//try to gather lock again results deadlock. | |
pthread_mutex_lock(&lock); | |
unsigned long i = 0; | |
counter += 1; | |
printf("\n Job %d has started\n", counter); | |
for (i = 0; i < (0xFFFFFFFF); i++) | |
; | |
printf("\n Job %d has finished\n", counter); | |
pthread_mutex_unlock(&lock); | |
return NULL; | |
} |
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 <pthread.h> | |
pthread_mutex_t recursive_mutex; | |
int avar; | |
void recursive_function(int n) { | |
pthread_mutex_lock(&recursive_mutex); | |
if (n > 0) { | |
avar = n; | |
printf("Entering recursive_function with n = %d , avar = %d\n", n, avar); | |
recursive_function(n - 1); | |
} | |
printf("Exiting recursive_function with n = %d, avar = %d\n", n, avar); | |
pthread_mutex_unlock(&recursive_mutex); | |
} | |
int main() { | |
pthread_mutexattr_t mutex_attr; | |
pthread_mutexattr_init(&mutex_attr); | |
pthread_mutexattr_settype(&mutex_attr, PTHREAD_MUTEX_RECURSIVE); | |
pthread_mutex_init(&recursive_mutex, &mutex_attr); | |
recursive_function(3); | |
pthread_mutex_destroy(&recursive_mutex); | |
pthread_mutexattr_destroy(&mutex_attr); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment