/*********************************************************************************
|
* Copyright: (C) 2025 LingYun IoT System Studio
|
* All rights reserved.
|
*
|
* Filename: deadlock.c
|
* Description: This file is deadlock example program.
|
*
|
* Version: 1.0.0(11/04/2025)
|
* Author: Guo Wenxue <guowenxue@gmail.com>
|
* ChangeLog: 1, Release initial version on "11/04/2025 05:43:15 PM"
|
*
|
********************************************************************************/
|
|
#include <stdio.h>
|
#include <unistd.h>
|
#include <pthread.h>
|
|
pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER;
|
pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER;
|
|
void *thread1(void *arg)
|
{
|
pthread_mutex_lock(&lock1); // 获取锁1
|
sleep(1); // 确保thread2能获取锁2
|
pthread_mutex_lock(&lock2); // 请求锁2 → 死锁!
|
printf("Thread1 got both locks\n");
|
pthread_mutex_unlock(&lock2);
|
pthread_mutex_unlock(&lock1);
|
return NULL;
|
}
|
|
void *thread2(void *arg)
|
{
|
pthread_mutex_lock(&lock2); // 获取锁2
|
sleep(1); // 确保thread1能获取锁1
|
pthread_mutex_lock(&lock1); // 请求锁1 → 死锁!
|
printf("Thread2 got both locks\n");
|
pthread_mutex_unlock(&lock1);
|
pthread_mutex_unlock(&lock2);
|
return NULL;
|
}
|
|
|
int main (int argc, char **argv)
|
{
|
pthread_t t1, t2;
|
|
pthread_create(&t1, NULL, thread1, NULL);
|
pthread_create(&t2, NULL, thread2, NULL);
|
|
pthread_join(t1, NULL);
|
pthread_join(t2, NULL);
|
return 0;
|
}
|