条件锁的使用

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值