yeonxhan_88
New Member
#include <stdio.h>
#include <pthread.h>
pthread_mutex_t lock1, lock2;
void* thread1(void* arg) {
// Acquire lock1
pthread_mutex_lock(&lock1);
// Simulate some work
printf("Thread 1 is trying to acquire the lock..\nTHERE IS A DEADLOCK SITUATION!!!\n");
sleep(1);
// Acquire lock2
pthread_mutex_lock(&lock2);
// Critical section
printf("Thread 1 is in the critical section.\n");
// Release lock2
pthread_mutex_unlock(&lock2);
// Release lock1
pthread_mutex_unlock(&lock1);
pthread_exit(NULL);
}
void* thread2(void* arg) {
// Acquire lock2
pthread_mutex_lock(&lock2);
// Simulate some work
printf("Thread 2 is trying to acquire the lock\n");
sleep(1);
// Acquire lock1
pthread_mutex_lock(&lock1);
// Critical section
printf("Thread 2 is in the critical section.\n");
// Release lock1
pthread_mutex_unlock(&lock1);
// Release lock2
pthread_mutex_unlock(&lock2);
pthread_exit(NULL);
}
int main() {
pthread_t tid1, tid2;
// Initialize locks
pthread_mutex_init(&lock1, NULL);
pthread_mutex_init(&lock2, NULL);
// Create thread 1
pthread_create(&tid1, NULL, thread1, NULL);
// Create thread 2
pthread_create(&tid2, NULL, thread2, NULL);
// Wait for threads to finish
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
// Destroy locks
pthread_mutex_destroy(&lock1);
pthread_mutex_destroy(&lock2);
return 0;
}
#include <pthread.h>
pthread_mutex_t lock1, lock2;
void* thread1(void* arg) {
// Acquire lock1
pthread_mutex_lock(&lock1);
// Simulate some work
printf("Thread 1 is trying to acquire the lock..\nTHERE IS A DEADLOCK SITUATION!!!\n");
sleep(1);
// Acquire lock2
pthread_mutex_lock(&lock2);
// Critical section
printf("Thread 1 is in the critical section.\n");
// Release lock2
pthread_mutex_unlock(&lock2);
// Release lock1
pthread_mutex_unlock(&lock1);
pthread_exit(NULL);
}
void* thread2(void* arg) {
// Acquire lock2
pthread_mutex_lock(&lock2);
// Simulate some work
printf("Thread 2 is trying to acquire the lock\n");
sleep(1);
// Acquire lock1
pthread_mutex_lock(&lock1);
// Critical section
printf("Thread 2 is in the critical section.\n");
// Release lock1
pthread_mutex_unlock(&lock1);
// Release lock2
pthread_mutex_unlock(&lock2);
pthread_exit(NULL);
}
int main() {
pthread_t tid1, tid2;
// Initialize locks
pthread_mutex_init(&lock1, NULL);
pthread_mutex_init(&lock2, NULL);
// Create thread 1
pthread_create(&tid1, NULL, thread1, NULL);
// Create thread 2
pthread_create(&tid2, NULL, thread2, NULL);
// Wait for threads to finish
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
// Destroy locks
pthread_mutex_destroy(&lock1);
pthread_mutex_destroy(&lock2);
return 0;
}

