Linux系统编程--线程同步(条件变量+互斥锁)

声明

以下内容仅供学习,如有侵权,联系作者删除。
参考文献:B站up主:C语言技术网
链接: C语言技术网–条件变量与互斥锁

条件变量+互斥锁

int pthread_cond_wait(pthread_cond_t *restrict cond,
              pthread_mutex_t *restrict mutex);
note: 1)释放互斥锁
	  2)等待条件
	  3)条件被触发,给互斥锁加锁
/*
 * 程序启动后,等待条件满足,唤醒线程,执行线程函数。
 * 作者:jack 日期:20210619
 * 参考作者:C语言技术网(www.freecplus.net), B站UP主:C语言技术网
*/
#include <stdio.h>
#include <pthread.h>
#include<unistd.h>
#include <signal.h>

pthread_mutex_t mutex;  // 声明互斥锁
pthread_cond_t cond;    // 声明条件变量

void *thread1(void *arg)
{
  while(1)
  {
    pthread_mutex_lock(&mutex);
    printf("线程一开始等待条件。\n");  
    pthread_cond_wait(&cond, &mutex);
    printf("线程一被唤醒。\n");  
    pthread_mutex_unlock(&mutex);
  }

}

void *thread2(void *arg)
{
  while(1)
  {
    pthread_mutex_lock(&mutex);
    printf("线程二开始等待条件。\n");  
    pthread_cond_wait(&cond, &mutex);
    printf("线程二被唤醒。\n");  
    pthread_mutex_unlock(&mutex);
  }

}
void func(int sig)
{
  pthread_cond_signal(&cond);
  //pthread_cond_broadcast(&cond);
}

int main()
{
  signal(15, func);

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

  pthread_t pthid1, pthid2;

  pthread_create(&pthid1, NULL, thread1, (void *)1);
  pthread_create(&pthid2, NULL, thread2, (void *)2);

  pthread_join(pthid1, NULL);
  pthread_join(pthid2, NULL);

  return 0;
}

运行结果:
在这里插入图片描述

小结

结果处理比较麻烦,建议大家去看视频(视频链接在文章头部)。代码直接复制我的可以先跑起来,然后在改动调试。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值