linux C编程之死锁

死锁:

死锁就是你和小明打架,互相掐住对方脖子,你们都说“你先放!”,结果谁都不放,死锁了.
在程序里面,有两个锁,A线程锁住第一个,B线程锁住了第二个,这时如果A再试图锁第二个,失败,因为B已经锁住了,A只能等待.就在这时B试图锁第一个,结果失败,因为A已经锁住了,B只好等待.就这样大家一直等下去,谁都不放,天荒地老...

举例:

#include <unistd.h> 
#include <pthread.h> 
#include <string.h> 

pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; 
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER; 
pthread_mutex_t mutex3 = PTHREAD_MUTEX_INITIALIZER; 
pthread_mutex_t mutex4 = PTHREAD_MUTEX_INITIALIZER; 

static int sequence1 = 0; 
static int sequence2 = 0; 

 int func1() 
 { 
    pthread_mutex_lock(&mutex1); 
    ++sequence1; 
    sleep(1); 
    pthread_mutex_lock(&mutex2); 
    ++sequence2; 
    pthread_mutex_unlock(&mutex2); 
    pthread_mutex_unlock(&mutex1); 

    return sequence1; 
 } 

 int func2() 
 { 
    pthread_mutex_lock(&mutex2); 
    ++sequence2; 
    sleep(1); 
    pthread_mutex_lock(&mutex1); 
    ++sequence1; 
    pthread_mutex_unlock(&mutex1); 
    pthread_mutex_unlock(&mutex2); 

    return sequence2; 
 } 

 void* thread1(void* arg) 
 { 
    while (1) 
    { 
        int iRetValue = func1(); 

        if (iRetValue == 100000) 
        { 
            pthread_exit(NULL); 
        } 
    } 
 } 

 void* thread2(void* arg) 
 { 
    while (1) 
    { 
        int iRetValue = func2(); 

        if (iRetValue == 100000) 
        { 
            pthread_exit(NULL); 
        } 
    } 
 } 

 void* thread3(void* arg) 
 { 
    while (1) 
    { 
        sleep(1); 
        char szBuf[128]; 
        memset(szBuf, 0, sizeof(szBuf)); 
        strcpy(szBuf, "thread3"); 
    } 
 } 

 void* thread4(void* arg) 
 { 
    while (1) 
    { 
        sleep(1); 
        char szBuf[128]; 
        memset(szBuf, 0, sizeof(szBuf)); 
        strcpy(szBuf, "thread3"); 
    } 
 } 

 int main() 
 { 
    pthread_t tid[4]; 
    if (pthread_create(&tid[0], NULL, &thread1, NULL) != 0) 
    { 
        _exit(1); 
    } 
    if (pthread_create(&tid[1], NULL, &thread2, NULL) != 0) 
    { 
        _exit(1); 
    } 
    if (pthread_create(&tid[2], NULL, &thread3, NULL) != 0) 
    { 
        _exit(1); 
    } 
    if (pthread_create(&tid[3], NULL, &thread4, NULL) != 0) 
    { 
        _exit(1); 
    } 

    sleep(5); 
    //pthread_cancel(tid[0]); 

    pthread_join(tid[0], NULL); 
    pthread_join(tid[1], NULL); 
    pthread_join(tid[2], NULL); 
    pthread_join(tid[3], NULL); 

    pthread_mutex_destroy(&mutex1); 
    pthread_mutex_destroy(&mutex2); 
    pthread_mutex_destroy(&mutex3); 
    pthread_mutex_destroy(&mutex4); 

    return 0; 
 }

gcc dead_lock.c -g -lpthread -o dead_lock
./dead_lock 

分析:

gdb调试

从图看出了,thread 5持有31952想要31953, 而thread 5持有31953想要31952

 

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值