条件锁的使用

Linux 专栏收录该内容
8 篇文章 0 订阅
#include<pthread.h>
#include<unistd.h>
#include<iostream>
#include<time.h>
#include<errno.h>
#include<sys/time.h>
using namespace std;

// 初始化互斥量
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

// 初始化条件变量
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

// 进程是否终止
bool terminal = 1;

// 唤醒所有线程
void notifyAll()
{
 int ret;
 ret = pthread_mutex_lock(&mutex);
 if(ret < 0)
 {
  cerr << "mutex lock error:" << ret << endl;

  return ;
 }
  
 // 改变条件
    terminal = 0;

 // 通知所有线程,条件已经改变
 ret = pthread_cond_broadcast(&cond); 
 if(ret < 0)
 {
  cerr << "pthread_cond_broadcast error : " << ret << endl;
 }

 ret = pthread_mutex_unlock(&mutex);
 if(ret < 0)
 {
  cerr << "pthread_mutex_unlock error :" << ret << endl;

  return;
 }
}

void *thread1(void *arg)
{
 int i = 0;

 struct timeval tp;
 struct timespec time;
 int ret;
    
  while(terminal)
  {

  // 等待时间设为3s
  gettimeofday(&tp,NULL);
        time.tv_sec = tp.tv_sec;
        time.tv_nsec = tp.tv_usec * 1000;
        time.tv_sec += 3;
  i++;
  cout << pthread_self() << "|" << i << endl;

  
  // 调用pthread_cond_timedwait前必须给互斥量加锁
  ret = pthread_mutex_lock(&mutex);
  if(ret < 0)
  {
   cout << "pthread_mutex_lock error:" << ret << endl;
   pthread_exit(NULL); 
  }

  ret = pthread_cond_timedwait(&cond,&mutex,&time);
  if(ret < 0)
  {
   cerr << "pthread_cond_timedwait error:" << ret << endl;

   pthread_exit(NULL);
  }
        if(ret == ETIMEDOUT)
  {
   cout << pthread_self() << " time out " << endl;
  }
  else
  {
   cout << pthread_self() << " cond change" << endl; 
  }
  sleep(1);
  ret = pthread_mutex_unlock(&mutex);
  if(ret < 0)
  {
   cerr << "pthread_mutex_unlock error:" << ret << endl;
   pthread_exit(NULL);
  }

  }
}

int main()
{
 // 创建两个线程
 pthread_t tid1,tid2;
 pthread_create(&tid1,NULL,thread1,NULL);
 pthread_create(&tid2,NULL,thread1,NULL);
	
	

 sleep(1);
 notifyAll();
	
 sleep(5);
 pthread_join(tid1,NULL);
 pthread_join(tid2,NULL);

 return 0;
}

展开阅读全文
  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值