什么情况造成死锁

什么是死锁?
所谓死锁,是指多个进程在运行过程中因争夺资源而造成的一种僵局,当进程处于这种僵持状态时,若无外力作用,它们都将无法再向前推进。 因此我们举个例子来描述,如果此时有一个线程A,按照先锁a再获得锁b的的顺序获得锁,而在此同时又有另外一个线程B,按照先锁b再锁a的顺序获得锁。如下图所示:

产生死锁的原因?
可归结为如下两点:

a. 竞争资源

系统中的资源可以分为两类:
可剥夺资源,是指某进程在获得这类资源后,该资源可以再被其他进程或系统剥夺,CPU和主存均属于可剥夺性资源;
另一类资源是不可剥夺资源,当系统把这类资源分配给某进程后,再不能强行收回,只能在进程用完后自行释放,如磁带机、打印机等。
产生死锁中的竞争资源之一指的是竞争不可剥夺资源(例如:系统中只有一台打印机,可供进程P1使用,假定P1已占用了打印机,若P2继续要求打印机打印将阻塞)
产生死锁中的竞争资源另外一种资源指的是竞争临时资源(临时资源包括硬件中断、信号、消息、缓冲区内的消息等),通常消息通信顺序进行不当,则会产生死锁
b. 进程间推进顺序非法

若P1保持了资源R1,P2保持了资源R2,系统处于不安全状态,因为这两个进程再向前推进,便可能发生死锁
例如,当P1运行到P1:Request(R2)时,将因R2已被P2占用而阻塞;当P2运行到P2:Request(R1)时,也将因R1已被P1占用而阻塞,于是发生进程死锁
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>

  // int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
  //                    void *(*start_routine) (void *), void *arg);

int g_data = 0;
pthread_mutex_t mutex;
pthread_mutex_t mutex2;
void *thread_func(void arg)
{
printf(“t1: %ld thread is create\n”,(unsigned long)pthread_self());
printf(“t1:param is %d\n”,
((int *)arg));
pthread_mutex_lock(&mutex);
sleep(1);
pthread_mutex_lock(&mutex2);
while(1) {
printf(“t1 = %d\n”,g_data++);
sleep(1);
if(g_data == 3){
pthread_mutex_unlock(&mutex);
printf(“t1 quit ==============\n”);
pthread_exit(NULL);
}
}

}

void *thread_func1(void arg)
{
printf(“t2: %ld thread is create\n”,(unsigned long)pthread_self());
printf(“t2:param is %d\n”,
((int *)arg));
while(1) {
printf(“t2 = %d\n”,g_data);
pthread_mutex_lock(&mutex2);
sleep(1);
pthread_mutex_lock(&mutex);
g_data++;
pthread_mutex_unlock(&mutex);
sleep(1);
}

}
int main()
{
int ret;
int param = 100;
pthread_t t1;
pthread_t t2;
pthread_mutex_init(&mutex,NULL);
pthread_mutex_init(&mutex2,NULL);
ret = pthread_create(&t1,NULL,thread_func,(void *)&param);
if(ret == 0){
printf(“main: create t1 success\n”);
}
ret = pthread_create(&t2,NULL,thread_func1,(void *)&param);
if(ret == 0){
printf(“main: create t2 success\n”);
}

    printf("main:%ld\n",(unsigned long)pthread_self());
    while(1) {
            printf("main = %d\n",g_data);
            sleep(1);
    }

    pthread_join(t1,NULL);
    pthread_join(t2,NULL);
    pthread_mutex_destroy(&mutex);
    pthread_mutex_destroy(&mutex2);
    return 0;

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值