Linux线程同步--死锁

死锁

假如我有两个以上的锁,我线程1已经获得锁1,想要获得锁2,而我线程2已经获得锁2,想要获得锁1,现在双方都获取不到自己想要的东西,就会一直等待,这就是死锁。

线程同步

pthread_cond_t创建条件变量

pthread_cond_t cond; // 定义一个条件变量,是一个结构体

int pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr);

brief:初始化条件变量(条件变量是利用全局变量进行同步的机制)

param:第一个参数是要初始化的条件变量,第二个参数,NULL

return:成功返回0 ,

pthread_cond_wait等待条件变量

int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex);

brief:第一次调用会自动释放锁堵塞在这里等待被唤醒,被唤醒后自动上锁

param:第一个参数,条件变量的地址,第二个参数,锁的地址(条件变量必须配合互斥锁使用)

return:成功返回0

pthread_cond_signal唤醒线程

int pthread_cond_signal(pthread_cond_t *cond);

brief:唤醒阻塞的线程,唤醒的线程从堵塞处开始执行

param:条件变量的地址

return:成功返回0

pthread_cond_destroy销毁条件变量

int pthread_cond_destroy(pthread_cond_t *cond);

brief:销毁条件变量

param:需要销毁的条件变量的地址

return:成功返回0


#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>

int data = 0;
pthread_mutex_t mutex;
pthread_cond_t cond;

void * handler1(void * argc)
{


        //while(1)//while里面可以不用写解锁,因为再次调用wait的时候,就已经释放锁了
//      {        //如果不用while,则必须解锁,不然线程1退出过后,线程2 获取不到锁就会堵塞

                pthread_cond_wait(&cond,&mutex);

                printf("t1:%d\n",data);
                data = 0;

                printf("没错就是这样\n");
//      }
                pthread_mutex_unlock(&mutex);
}

void * handler2(void * argc)
{
        while(1)
        {
                pthread_mutex_lock(&mutex);

                printf("t2:%d\n",data);
                data++;
                if(data == 3)
                {
                        pthread_cond_signal(&cond);
                }

                pthread_mutex_unlock(&mutex);
                sleep(1);
        }
}

void main()
{
        pthread_t t1;
        pthread_t t2;

        pthread_mutex_init(&mutex,NULL);
        pthread_cond_init(&cond,NULL);

        pthread_create(&t1,NULL,handler1,NULL);
        pthread_create(&t2,NULL,handler2,NULL);



        pthread_join(t1,NULL);
        pthread_join(t2,NULL);

        pthread_mutex_destroy(&mutex);
        pthread_cond_destroy(&cond);
}

我们可以编一个程序来记录我们跑10次

#include <stdio.h>
​
void main(int argc,char **argv)
{
​
    int time = atoi(argv[1]);
    int i;
    
    for(i = 0;i < time;++i)
    {
        system("./pp");
    
    }
​
​
}

编译测试程序后输入./a.out 10 >>test & 10是运行十次的意思 &是后台运行 运行完后,打开test可以看到10次运行效果都写入到文件里了

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

No Iverson

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值