APUE course source code
guowenxue
yesterday 7b55c92f8d1401a93c8fd8e342da271dce742000
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/*********************************************************************************
 *      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;
}