Linux 线程-条件变量

本文通过C++实现了一个典型的生产者-消费者模式案例,利用线程间的同步互斥锁及条件变量来确保链表中数据的安全操作。生产者不断地生成随机数并将其插入到链表头部,而消费者则从链表中移除元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值