#include #include #include // Declare two global mutexes pthread_mutex_t lockA; pthread_mutex_t lockB; // Thread 1 task void* threadOneTask(void* arg) { printf("Thread 1: Attempting to lock Mutex A...\n"); pthread_mutex_lock(&lockA); printf("Thread 1: Successfully locked Mutex A.\n"); // Sleep briefly to allow Thread 2 to lock Mutex B usleep(50000); printf("Thread 1: Attempting to lock Mutex B...\n"); pthread_mutex_lock(&lockB); // Thread 1 hangs here forever printf("Thread 1: Successfully locked Mutex B.\n"); // Unlock resources (this code is never reached) pthread_mutex_unlock(&lockB); pthread_mutex_unlock(&lockA); return NULL; } // Thread 2 task void* threadTwoTask(void* arg) { printf("Thread 2: Attempting to lock Mutex B...\n"); pthread_mutex_lock(&lockA); //pthread_mutex_lock(&lockB); printf("Thread 2: Successfully locked Mutex B.\n"); // Sleep briefly to allow Thread 1 to lock Mutex A usleep(50000); printf("Thread 2: Attempting to lock Mutex A...\n"); pthread_mutex_lock(&lockB); //pthread_mutex_lock(&lockA); // Thread 2 hangs here forever printf("Thread 2: Successfully locked Mutex A.\n"); // Unlock resources (this code is never reached) //pthread_mutex_unlock(&lockA); pthread_mutex_unlock(&lockB); pthread_mutex_unlock(&lockA); return NULL; } int main() { pthread_t thread1, thread2; // Initialize the mutexes pthread_mutex_init(&lockA, NULL); pthread_mutex_init(&lockB, NULL); // Create the two threads pthread_create(&thread1, NULL, threadOneTask, NULL); pthread_create(&thread2, NULL, threadTwoTask, NULL); // Wait for threads to finish (they never will) pthread_join(thread1, NULL); pthread_join(thread2, NULL); // Clean up mutexes (never reached) pthread_mutex_destroy(&lockA); pthread_mutex_destroy(&lockB); return 0; }