Linux 线程-条件变量

#include <cstdio>
#include<pthread.h>
#include <iostream>
#include<unistd.h>
#include<string.h>

using namespace std;

//节点结构
typedef struct node {
    int data;
    struct node* next;
}Node;
//永远指向链表头部的指针
Node *head = NULL;
//线程同步-互斥锁
pthread_mutex_t mutex;
//条件变量-阻塞线程
pthread_cond_t cond;

//生产者
void* producer(void *arg) {

    while (1) {
        Node* p = new Node;
        //Node * p = (Node*)malloc(sizeof(Node));
        p->data = rand() % 1000;
        pthread_mutex_lock(&mutex);
        p->next = head;
        head = p;
        cout << "====produce:" << pthread_self() << "  " << p->data << endl;
        pthread_mutex_unlock(&mutex);
        pthread_cond_signal(&cond);
        sleep(rand() % 3);
    }
    return NULL;
}
void* customer(void *arg) {

    while (1) {
        pthread_mutex_lock(&mutex);
        if (head == NULL) {
            pthread_cond_wait(&cond, &mutex);

        }
        Node* pdel = head;
        head = head->next;
        cout << "--------customer: " << pthread_self() << " " << pdel->data << endl;
        delete pdel;
        pthread_mutex_unlock(&mutex);
    }
    return NULL;
}


int main()
{
    pthread_t p1, p2;

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



    //创建生产者线程
    pthread_create(&p1, NULL, producer, NULL);
    //创建消费者线程
    pthread_create(&p2, NULL, customer, NULL);


    //阻塞回收子线程
    pthread_join(p1, NULL);
    pthread_join(p2, NULL);



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值