多线程造成死锁的两种情况

*
 * 程序中使用一个以上的互斥量造成程序死锁
 */
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
//定义两个互斥锁并初始化
pthread_mutex_t ALock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t BLock = PTHREAD_MUTEX_INITIALIZER;

/*
 * 功能:线程1函数
 */
void* thread1_func(void *arg)
{
    //sleep(1);
    pthread_mutex_lock(&ALock);
    sleep(2);
    printf("thread 1 lock ALock, wanting get BLock...\n");
    pthread_mutex_lock(&BLock);
    printf("thread 1 get BLock\n");
    pthread_mutex_unlock(&BLock);
    pthread_mutex_unlock(&ALock);
    pthread_exit(NULL);
}

/*
 * 功能:线程而2函数
 */
void* thread2_func(void *arg)
{
    sleep(1);
    pthread_mutex_lock(&BLock);
    printf("thread 2 lock BLock, wating get ALock...\n");
    pthread_mutex_lock(&ALock);
    printf("thread 2 get ALock\n");
    pthread_mutex_unlock(&ALock);
    pthread_mutex_unlock(&BLock);
    pthread_exit(NULL);
}

int main(void)
{
    pthread_t thid1, thid2;

    pthread_create(&thid1, NULL, thread1_func, NULL);
    pthread_create(&thid2, NULL, thread2_func, NULL);

    pthread_join(thid1, NULL);
    pthread_join(thid2, NULL);
    printf("main thread exit\n");
    exit(0);
}

#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
//在同一个线程对同一个互斥量加锁两次会出现死锁
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;//定义一个互斥量,并对其进行初始化
int a = 6;

/*void* thread_func(void *arg)
{
    pthread_mutex_lock(&lock);
    pthread_mutex_lock(&lock);
    printf("thread a = %d\n", a);
    pthread_mutex_unlock(&lock);
    pthread_exit(NULL);
}*/
int main(void)
{
    pthread_mutex_lock(&lock);
    pthread_mutex_lock(&lock);//对一个互斥量加锁两次,出现死锁
    printf("%d\n", a);//永远不会执行到这里
    pthread_mutex_unlock(&lock);
    exit(EXIT_SUCCESS);

/*  int err;
    pthread_t thid;

    err = pthread_create(&thid, NULL, thread_func, NULL);
    if(err != 0)
    {
        printf("pthread_create failed\n");
        exit(EXIT_FAILURE);
    }
    pthread_join(thid, NULL);
    printf("main thread a = %d\n",a);
    exit(EXIT_SUCCESS);*/
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值