Linux信号量(简易版)

Sem.hpp(用于封装信号量):

cpp 复制代码
#include<iostream>
#include<queue>
#include<unistd.h>
#include <semaphore.h>
using namespace std;
class Sem
{
public:
    Sem(int num)
    {
        sem_init(&_sem,0,num);
    }
    ~Sem()
	{
		sem_destroy(&_sem);
	}
    void V()
    {
        sem_post(&_sem);
    }
    void P()
    {
        sem_wait(&_sem);
    }
private:
    sem_t _sem;
};

Task.hpp(封装任务队列):

cpp 复制代码
#include "sem.hpp"
#include <iostream>
#include <queue>
#include <pthread.h>
using namespace std;

int num = 10;

class Task
{
public:
    Task(): _space(num), _data(0)
    {
        pthread_mutex_init(&_mtx, nullptr);
    }

    void Push(int x)
    {
        _space.P();  // 生产者等待空间
        pthread_mutex_lock(&_mtx);
        q.push(x);
        cout << "生产了:" << x << endl;
        pthread_mutex_unlock(&_mtx);
        _data.V();   // 通知消费者数据已生产
    }

    void Pop()
    {
        _data.P();   // 消费者等待数据
        pthread_mutex_lock(&_mtx);
        cout << "消费了:" << q.front() << endl;
        q.pop();
        pthread_mutex_unlock(&_mtx);
        _space.V();  // 通知生产者空间已释放
    }

private:
    Sem _space;    // 空闲空间数量
    Sem _data;     // 数据数量
    pthread_mutex_t _mtx;
    queue<int> q;
};

.cc:

cpp 复制代码
#include"Task.hpp"
void* consumer(void* args)
{
    Task* t = (Task*)args;
    while(1)
    {
        sleep(1);
        t->Pop();
    }
    return nullptr;
}
void* producer(void* args)
{
    Task* t = (Task*)args;
    while(1)
    {
        t->Push(rand()%1000);
    }
    return nullptr;
}
int main()
{
    srand(time(nullptr));
    Task* t = new Task;
    pthread_t Consumer[5];
    pthread_t Producer[5];
    for(int i = 0; i < 5; i++)
    {
        pthread_create(&Consumer[i], nullptr, consumer, (void*)t);
        pthread_create(&Producer[i], nullptr, producer, (void*)t);
    }
    for(int i = 0; i < 3; i++)
    {
        pthread_join(Consumer[i], nullptr);
        pthread_join(Producer[i], nullptr);
    }
    delete t;
    return 0;
}   
相关推荐
KingRumn1 分钟前
Linux信号之标准信号与实时信号
linux·算法
QT 小鲜肉2 小时前
【Linux命令大全】001.文件管理之git命令(实操篇)
linux·服务器·笔记·git·elasticsearch
sishen41993 小时前
嵌入式Linux没有学习方向怎么办,嵌入式Linux怎么学
linux
逆风水手3 小时前
Ansible自动化运维入门指南
linux·运维·自动化·ansible
旖旎夜光4 小时前
Linux(3)(下)
linux·学习
小鹿学程序5 小时前
任务一-1.子任务一:基础环境准备
linux·bigdata
Nautiluss5 小时前
一起玩XVF3800麦克风阵列(十)
linux·人工智能·python·音频·语音识别·实时音视频·dsp开发
悲喜自渡7215 小时前
Python 编程(gem5 )
java·linux·开发语言
不怕犯错,就怕不做5 小时前
RK3562 +RK817的dts布尔属性解析(uboot基础知识)
linux·驱动开发·嵌入式硬件
广州灵眸科技有限公司6 小时前
瑞芯微(EASY EAI)RV1126B 音频输入
linux·开发语言·网络·音视频