linux 条件变量 线程锁 线程

#include <iostream>
#include<pthread.h>
#include<unistd.h>
#include<time.h>
#include<stdlib.h>
using namespace std;
/*
测试条件变量
用到条件变量和线程锁 链表
例子为生产者和消费者,
原则是生产者有生产出物品,消费者才可以消费
*/

//结构体
typedef struct _node
{
    int data;
    struct _node *next_node;
} Node;

//头节点
Node*headNode=NULL; //初始化头节点为空
pthread_mutex_t mutex_t; //线程锁对象
pthread_cond_t cond_t;  //条件变量对象
void*fun1(void*arg) //生产者
{
  while(1)  //无限生产
  {
      Node*newnode=new Node;  //新建结构体对象
      newnode->data=rand()%100;

      pthread_mutex_lock(&mutex_t); //上锁
      newnode->next_node=headNode;
      headNode=newnode;

      printf("====== fun1: %lu, %d\n", pthread_self(), newnode->data);

      pthread_mutex_unlock(&mutex_t);//解锁
      pthread_cond_signal(&cond_t);//发送条件变量信号
      sleep(rand()%3+1);
  }
  return NULL;
}

void*fun2(void*arg)//消费者
{
  while(1)
  {
      pthread_mutex_lock(&mutex_t);//上锁
      if(headNode == NULL)
      {
          pthread_cond_wait(&cond_t,&mutex_t);//条件变量阻塞
      }
      Node*temp=headNode;
      printf("====== fun2: %lu, %d\n", pthread_self(), headNode->data);
      headNode=headNode->next_node;
      delete temp;
      pthread_mutex_unlock(&mutex_t);//解锁
      sleep(rand()%6+1);
  }
   return NULL;
}

int main()
{


   pthread_t pid1,pid2; //线程变量
   pthread_mutex_init(&mutex_t,NULL);//线程锁初始化
   pthread_cond_init(&cond_t,NULL);//条件变量初始化

   pthread_create(&pid1,NULL,fun1,NULL);//创建线程
   pthread_create(&pid2,NULL,fun2,NULL);//创建线程

   pthread_join(pid1,NULL);//等待回收线程资源
   pthread_join(pid2,NULL);//等待回收线程资源

   pthread_mutex_destroy(&mutex_t);//销毁线程锁
   pthread_cond_destroy(&cond_t);//销毁条件变量
    return 0;
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值