#include #include #include #include #include pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex3 = PTHREAD_MUTEX_INITIALIZER; void* process_fun(void* arg) { int id = *(int*)arg; bool success = false; pthread_mutex_t* mutexs[3]; if (id == 0) { // Gives deadlock sometimes mutexs[0] = &mutex1; mutexs[1] = &mutex2; mutexs[2] = &mutex3; } else if (id == 1) { mutexs[0] = &mutex2; mutexs[1] = &mutex1; mutexs[2] = &mutex3; } else if (id == 2) { mutexs[0] = &mutex1; mutexs[1] = &mutex2; mutexs[2] = &mutex3; } while (!success) { bool csucc = true; for (int i=0; i < 3; i++) { if (pthread_mutex_trylock(mutexs[i]) != 0) { for (int j=0; j < i; j++) { pthread_mutex_unlock(mutexs[i]); } csucc = false; break; } } success = csucc; } printf("I have access\n"); pthread_mutex_unlock(mutexs[0]); pthread_mutex_unlock(mutexs[1]); pthread_mutex_unlock(mutexs[2]); return NULL; } int main() { pthread_t tid[3]; int args[3]; for (int i=0; i < 3; i++) { args[i] = i; pthread_create(&(tid[i]), NULL, &process_fun, &(args[i])); } for (int i=0; i < 3; i++) { pthread_join(tid[i], NULL); } }