Skip to content

Instantly share code, notes, and snippets.

@barron9
Last active August 10, 2023 06:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barron9/92bd5f03c9fede2df70b6ef186a0bee5 to your computer and use it in GitHub Desktop.
Save barron9/92bd5f03c9fede2df70b6ef186a0bee5 to your computer and use it in GitHub Desktop.
deadlock example
#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;
}
#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