Linux——生产者消费者模型和信号量

目录​​​​​​​

基于BlockingQueue的生产者消费者模型

概念

条件变量的第二个参数的作用

 锁的作用

生产者消费者模型的高效性

生产者而言,向blockqueue里面放置任务

消费者而言,从blockqueue里面拿取任务:

总结

完整代码(不含存储数据的线程)

完整代码(含存储线程) 

信号量

1、先发现我们之前写的代码不足的地方。

 关于临界资源

总结

信号量的概念

申请信号量的本质

申请信号量的情况

信号量作为计数器的操作

信号量相关函数

初始化信号量

等待信号量

发布信号量

基于RingQueue的生产者消费者模型

引入环形队列

 生产和消费在什么情况下可能访问同一个位置

 举个例子

生产者而言

消费者而言

总结 

环形队列的实现(代码)


基于BlockingQueue的生产者消费者模型

概念

在多线程编程中阻塞队列(Blocking Queue)是一种常用于实现生产者和消费者模型的数据结构。
其与普通的队列区别在于:
    当队列为空时,从队列获取元素的操作将会被阻塞,直到队列中被放入了元素;
    当队列满时,往队列里存放元素的操作也会被阻塞,直到有元素被从队列中取出(以上的操作都是基于不同的线程来说的,线程在对阻塞队列进程操作时会被阻塞)。

条件变量的第二个参数的作用

 因为如果队列为满那么对应进来的线程将等待(被挂起)
由于自身已经拥有锁的缘故,锁就不会被释放了
将第二个参数的锁传过去的作用就是,如果该线程被挂起
那么对应的锁是会被释放的,以便于后边的线程可以申请锁成功

 锁的作用

在阻塞队列中,因为有锁的存在,无论外部的线程有多少,真正进入到我们的阻塞队列中生产或者消费的线程永远只有一个。

生产者消费者模型的高效性

生产者而言,向blockqueue里面放置任务

对于生产者,他的任务从哪里来的呢?它获取任务和构建任务要不要花时间??

生产者获取任务是要花时间的:
生产活动,从数据库?从网络,从外设??拿来的用户数据!!

消费者而言,从blockqueue里面拿取任务:


对于消费者,难道它把任务从任务队列中拿出来就完了吗??
消费者拿到任务之后,后续还有没有任务??

消费者拿任务这个过程,也可能非常耗时!!(计算或处理或存储)。


总结

可以在生产之前,和消费之后,让线程并行执行。

也就是说高效是体现在进入阻塞队列前的生产者并行的生产数据,和出阻塞队列后的消费者并行的消费数据。

完整代码(不含存储数据的线程)

里面含有 BlockQueue.hpp  MainCp.cc  Task.hpp(并且由详细的注释)

*********************************
BlockQueue.hpp
*********************************

#pragma once

#include <iostream>
#include <pthread.h>
#include <queue>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <cstdio>

const int gmaxcap = 5;

template <class T>
class BlockQueue
{
public:
   // 构造函数 主要完成阻塞队列的大小、锁、条件变量的初始化
    BlockQueue(const int &maxcap = gmaxcap) // 给一个缺省值(默认为gmaxcap)
    : _maxcap(maxcap)
    {
        // 都是局部的
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_pcond, nullptr);
        pthread_cond_init(&_ccond, nullptr);
    }

    // 向队列里面放数据
    void push(const T &in) // 输入型参数, const &
    {
        // 加锁
        pthread_mutex_lock(&_mutex);

        // 1、判断
        // 细节2:充当条件判断的语法必须是while,不能是if
        while (is_full()) // 如果队列中满的条件满足了,就不能生产了
        {
            // 细节1:pthread_cond_wait这个函数的第二个参数,必须是我们正在使用的互斥锁!

            // 因为如果队列为满那么对应进来的线程将等待(被挂起)
            // 由于自身已经拥有锁的缘故,锁就不会被释放了
            // 将第二个参数的锁传过去的作用就是,如果该线程被挂起
            // 那么对应的锁是会被释放的,以便于后边的线程可以申请锁成功

            // a、pthread_cond_wait:该函数调用的时候,会以原子性的方式,将锁释放,并将自己挂起
            // b、pthread_cond_wait:该函数在被唤醒返回的时候,会自动的重新获取你传入的锁
            pthread_cond_wait(&_pcond, &_mutex); // 因为我们的生产条件不满足,无法生产,我们的生产者进行等待
        }

        // 2、当走到这里一定是没有满的
        // 将需要放入的数据push进队列
        _q.push(in);

        // 3、绝对能保证,阻塞队列里面一定有数据,因此将消费者进行唤醒
        // 细节3:pthread_cond_signal:这个函数,可以放在临界区内部,也可以放在外部
        pthread_cond_signal(&_ccond); // 这里可以有一定的策略(比如高于多少数据再消费等等)
        
        // 解锁
        pthread_mutex_unlock(&_mutex);
    }


    // 向队列里面拿数据
    void pop(T *out) // 输出型参数:*, //输入型参数:&
    {
        // 为保证数据的安全,肯定是先加锁
        pthread_mutex_lock(&_mutex);
        // 1、判断
        while (is_empty()) // 如果队列中为空,就不能消费了
        {
            // 由于该函数可能调用失败,所以需要进行while循环以防调用失败后就直接向后执行了
            pthread_cond_wait(&_ccond, &_mutex);
        }
        // 2、走到这里我们能保证,一定不为空

        // 拿到头部结点
        *out = _q.front();

        // 将该数据pop掉
        _q.pop();

        // 3、绝对能保证,阻塞队列里面,至少有一个空的位置,因此将生产者进行唤醒
        pthread_cond_signal(&_pcond); // 这里可以有一定的策略(比如低于多少数据再生产等等)
        pthread_mutex_unlock(&_mutex);
    }

    // 出作用域由于自动调用析构函数,因此自动销毁
    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mutex);

        pthread_cond_destroy(&_pcond);
        pthread_cond_destroy(&_ccond);
    }

private:
    // 判断队列是否为空
    bool is_empty()
    {
        return _q.empty();
    }

    // 判断队列是否为满
    bool is_full()
    {
        return _q.size() == _maxcap;
    }

    


private:

    // 定义一个队列
    std::queue<T> _q;

    int _maxcap; // 表示队列的上限

    pthread_mutex_t _mutex;// 这个阻塞队列一定是临界资源(因此需要锁)

    pthread_cond_t _pcond; // 生产者对应的条件变量

    pthread_cond_t _ccond; // 消费者对应的条件变量
};



**********************************************
MainCp.cc
**********************************************
#include "BlockQueue.hpp"
#include "Task.hpp"
#include <time.h>

const std::string oper = "+-*/%";

int mymath(int x, int y, char op)
{
    int result = 0;
    switch (op)
    {
    case '+':
        result = x + y;
        break;
    case '-':
        result = x - y;
        break;
    case '*':
        result = x * y;
        break;

    case '/':
    {
        if (y == 0)
        {
            std::cerr << "mod zero error!" << std::endl;
            result = -1;
        }
        else
            result = x / y;
    }
    break;
    case '%':
    {
        if (y == 0)
        {
            std::cerr << "mod zero error!" << std::endl;
            result = -1;
        }
        else
            result = x % y;
    }
    break;
    default:
        break;
    }

    return result;
}

// 消费线程的消费动作
void *consumer(void *bq_)
{
    BlockQueue<Task> *bq = static_cast<BlockQueue<Task> *>(bq_);

    while (true)
    {
        // 消费活动
        // int data;
        Task t;
        bq->pop(&t); // 由于是输出型参数,因此是可以直接使用变量获取传入的变量的
        // std::cout << "消费数据:" << t._x << "+" << t._y << "=" << t() << std::endl;
        // std::cout << "消费数据:" << t.getx() << "+" << t.gety() << "=" << t() << std::endl;
        std::cout << "消费任务:" << t() << std::endl;

        // sleep(1);
    }

    return nullptr;
}

// 生产线程的生产动作
void *prodecter(void *bq_)
{
    BlockQueue<Task> *bq = static_cast<BlockQueue<Task> *>(bq_);

    while (true)
    {
        // 生产活动
        int x = rand() % 10; // 在这里我们先用随机数,构建一个数据
        int y = rand() % 5;

        int operCode = rand() % oper.size();
        // 定义一个Task对象
        Task t(x, y, oper[operCode], mymath);
        bq->push(t);
        std::cout << "生产任务:" << t.toTaskString() << std::endl;
        // sleep(1);
    }

    return nullptr;
}

int main()
{
    // 生成随机数种子:srand(time(nullptr));
    srand((unsigned long)time(nullptr) ^ getpid());

    // 为了让两个线程看到同一块资源
    BlockQueue<Task> *bq = new BlockQueue<Task>();

    // 定义线程
    pthread_t c, p;

    // 创建一个消费线程
    pthread_create(&c, nullptr, consumer, bq);
    // 创建一个生产线程
    pthread_create(&p, nullptr, prodecter, bq);

    // 等待线程
    pthread_join(c, nullptr);
    pthread_join(p, nullptr);

    delete bq;
    return 0;
}


*************************************************
Task.hpp
*************************************************
#pragma once

#include <iostream>
#include <functional>
#include <cstdio>

class Task
{

    using func_t = std::function<int(int, int, char)>;
    // typedef std::function<int(int, int)> func_t;

public:
    Task()
    {
    }

    Task(int x, int y, char op, func_t func)
        : _x(x), _y(y), _op(op), _callback(func)
    {
    }

    // 该函数是消费任务的打印信息
    std::string operator()()
    {
        int result = _callback(_x, _y, _op);
        char buffer[64];
        snprintf(buffer, sizeof(buffer), "%d %c %d = %d", _x, _op, _y, result);
        return buffer;
    }

// 该函数是生产任务的打印信息

    std::string toTaskString()
    {
        char buffer[64];
        snprintf(buffer, sizeof(buffer), "%d %c %d = ?", _x, _op, _y);
        return buffer;
    }

private:
    int _x;
    int _y;
    char _op;
    func_t _callback;
};






完整代码(含存储线程) 

里面含有 BlockQueue.hpp  MainCp.cc  Task.hpp(并且由详细的注释)

// BlockQueue.hpp

#pragma once

#include <iostream>
#include <pthread.h>
#include <queue>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <cstdio>

const int gmaxcap = 5;

template <class T>
class BlockQueue
{
public:
   // 构造函数 主要完成阻塞队列的大小、锁、条件变量的初始化
    BlockQueue(const int &maxcap = gmaxcap) // 给一个缺省值(默认为gmaxcap)
    : _maxcap(maxcap)
    {
        // 都是局部的
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_pcond, nullptr);
        pthread_cond_init(&_ccond, nullptr);
    }

    // 向队列里面放数据
    void push(const T &in) // 输入型参数, const &
    {
        // 加锁
        pthread_mutex_lock(&_mutex);

        // 1、判断
        // 细节2:充当条件判断的语法必须是while,不能是if
        while (is_full()) // 如果队列中满的条件满足了,就不能生产了
        {
            // 细节1:pthread_cond_wait这个函数的第二个参数,必须是我们正在使用的互斥锁!

            // 因为如果队列为满那么对应进来的线程将等待(被挂起)
            // 由于自身已经拥有锁的缘故,锁就不会被释放了
            // 将第二个参数的锁传过去的作用就是,如果该线程被挂起
            // 那么对应的锁是会被释放的,以便于后边的线程可以申请锁成功

            // a、pthread_cond_wait:该函数调用的时候,会以原子性的方式,将锁释放,并将自己挂起
            // b、pthread_cond_wait:该函数在被唤醒返回的时候,会自动的重新获取你传入的锁
            pthread_cond_wait(&_pcond, &_mutex); // 因为我们的生产条件不满足,无法生产,我们的生产者进行等待
        }

        // 2、当走到这里一定是没有满的
        // 将需要放入的数据push进队列
        _q.push(in);

        // 3、绝对能保证,阻塞队列里面一定有数据,因此将消费者进行唤醒
        // 细节3:pthread_cond_signal:这个函数,可以放在临界区内部,也可以放在外部
        pthread_cond_signal(&_ccond); // 这里可以有一定的策略(比如高于多少数据再消费等等)
        
        // 解锁
        pthread_mutex_unlock(&_mutex);
    }


    // 向队列里面拿数据
    void pop(T *out) // 输出型参数:*, //输入型参数:&
    {
        // 为保证数据的安全,肯定是先加锁
        pthread_mutex_lock(&_mutex);
        // 1、判断
        while (is_empty()) // 如果队列中为空,就不能消费了
        {
            // 由于该函数可能调用失败,所以需要进行while循环以防调用失败后就直接向后执行了
            pthread_cond_wait(&_ccond, &_mutex);
        }
        // 2、走到这里我们能保证,一定不为空

        // 拿到头部结点
        *out = _q.front();

        // 将该数据pop掉
        _q.pop();

        // 3、绝对能保证,阻塞队列里面,至少有一个空的位置,因此将生产者进行唤醒
        pthread_cond_signal(&_pcond); // 这里可以有一定的策略(比如低于多少数据再生产等等)
        pthread_mutex_unlock(&_mutex);
    }

    // 出作用域由于自动调用析构函数,因此自动销毁
    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mutex);

        pthread_cond_destroy(&_pcond);
        pthread_cond_destroy(&_ccond);
    }

private:
    // 判断队列是否为空
    bool is_empty()
    {
        return _q.empty();
    }

    // 判断队列是否为满
    bool is_full()
    {
        return _q.size() == _maxcap;
    }

    


private:

    // 定义一个队列
    std::queue<T> _q;

    int _maxcap; // 表示队列的上限

    pthread_mutex_t _mutex;// 这个阻塞队列一定是临界资源(因此需要锁)

    pthread_cond_t _pcond; // 生产者对应的条件变量

    pthread_cond_t _ccond; // 消费者对应的条件变量
};

// MainCp.cc
#include "BlockQueue.hpp"
#include "Task.hpp"
#include <time.h>

// 创建一个类
// 里面包含了BlockQueue类型的对象
// C:计算
// S:存储
template <class C, class S>
class BlockQueues
{
public:
    BlockQueue<C> *c_bq;
    BlockQueue<S> *s_bq;
};

// 消费线程的消费动作
void *consumer(void *bq_)
{
    // 先把传入的参数强转成BlockQueues<CalTask, SaveTask> *  类型的
    // 然后再指向自己的成员
    BlockQueue<CalTask> *bq = (static_cast<BlockQueues<CalTask, SaveTask> *>(bq_))->c_bq;

    BlockQueue<SaveTask> *save_bq = (static_cast<BlockQueues<CalTask, SaveTask> *>(bq_))->s_bq;

    while (true)
    {
        // 消费活动 
        // int data;
        CalTask t;
        bq->pop(&t);
        std::string result = t(); // 任务非常耗时!! 也是有可能的
        std::cout << "cal thread, 完成计算任务:" << result << " ... done" << std::endl;

        // // 调用SaveTask类中有参的构造函数来初始化对象save
        // SaveTask save(result, Save);
        // // 将savepush到save_bq存储队列里面
        // save_bq->push(save);

        // std::cout << "cal thread, 推送存储任务完成..." << std::endl;

        // sleep(1);
    }

    return nullptr;
}

// 生产线程的生产动作
void *prodecter(void *bq_)
{
    BlockQueue<CalTask> *bq = (static_cast<BlockQueues<CalTask, SaveTask> *>(bq_))->c_bq;
    while (true)
    {
        // 生产活动,从数据库?从网络,从外设??拿来的用户数据!!

        // 在这里x不可能为0,因此计算/和%的时候不需要考虑x为0的情况
        int x = rand() % 10 + 1; // 在这里我们先用随机数,构建一个数据
        int y = rand() % 5;

        int operCode = rand() % oper.size();
        // 定义一个Task对象
        CalTask t(x, y, oper[operCode], mymath);
        bq->push(t);
        std::cout << "prodecter thread, 生产计算任务:" << t.toTaskString() << std::endl;
        sleep(1);
    }

    return nullptr;
}

void *saver(void *bqs_)
{
    BlockQueue<SaveTask> *save_bq = (static_cast<BlockQueues<CalTask, SaveTask> *>(bqs_))->s_bq;

    while (true)
    {
        SaveTask t;
        save_bq->pop(&t);

        // 仿函数调用了Save方法
        // 因此保存了任务
        t();

        std::cout << "save thread, 保存任务完成..." << std::endl;
    }
}

int main()
{
    // 生成随机数种子:srand(time(nullptr));
    srand((unsigned long)time(nullptr) ^ getpid());

    BlockQueues<CalTask, SaveTask> bqs;

    // 为了让两个线程看到同一块资源
    bqs.c_bq = new BlockQueue<CalTask>();
    bqs.s_bq = new BlockQueue<SaveTask>();

    // 定义线程
    pthread_t c[2], p[3], s;

    // 创建消费线程
    pthread_create(c, nullptr, consumer, &bqs);
    pthread_create(c + 1, nullptr, consumer, &bqs);
    // 创建生产线程
    pthread_create(p, nullptr, prodecter, &bqs);
    pthread_create(p + 1, nullptr, prodecter, &bqs);
    pthread_create(p + 2, nullptr, prodecter, &bqs);
    // 保存一个线程
    // pthread_create(&s, nullptr, saver, &bqs);

    // 等待线程
    pthread_join(c[0], nullptr);
    pthread_join(c[1], nullptr);
    pthread_join(p[0], nullptr);
    pthread_join(p[1], nullptr);
    pthread_join(p[2], nullptr);
    // pthread_join(s, nullptr);

    delete bqs.c_bq;
    delete bqs.s_bq;
    return 0;
}

// Task.hpp

#pragma once

#include <iostream>
#include <functional>
#include <string>
#include <cstdio>

const std::string oper = "+-*/%";

int mymath(int x, int y, char op)
{
    int result = 0;
    switch (op)
    {
    case '+':
        result = x + y;
        break;
    case '-':
        result = x - y;
        break;
    case '*':
        result = x * y;
        break;

    case '/':
    {
        if (y == 0)
        {
            std::cerr << "mod zero error!" << std::endl;
            result = -1;
        }
        else
            result = x / y;
    }
    break;
    case '%':
    {
        if (y == 0)
        {
            std::cerr << "mod zero error!" << std::endl;
            result = -1;
        }
        else
            result = x % y;
    }
    break;
    default:
        break;
    }

    return result;
}

// 计算数据的类
class CalTask
{

    using func_t = std::function<int(int, int, char)>;
    // typedef std::function<int(int, int)> func_t;

public:
    CalTask()
    {
    }

    CalTask(int x, int y, char op, func_t func)
        : _x(x), _y(y), _op(op), _callback(func)
    {
    }

    // 该函数是消费任务的打印信息
    std::string operator()()
    {
        int result = _callback(_x, _y, _op);
        char buffer[64];
        snprintf(buffer, sizeof(buffer), "%d %c %d = %d", _x, _op, _y, result);
        return buffer;
    }

    // 该函数是生产任务的打印信息

    std::string toTaskString()
    {
        char buffer[64];
        snprintf(buffer, sizeof(buffer), "%d %c %d = ?", _x, _op, _y);
        return buffer;
    }

private:
    int _x;
    int _y;
    char _op;
    func_t _callback;
};

// 存储数据的类
class SaveTask
{
    typedef std::function<void(const std::string &)> func_t;

public:
    SaveTask()
    {
    }

    SaveTask(const std::string &message, func_t func)
        : _message(message), _func(func)
    {
    }

    // 其本质就是将任务存储到文件当中 -- 调用的是Save方法
    void operator()()
    {
        _func(_message);
    }

private:
    std::string _message;
    func_t _func;
};

void Save(const std::string &message)
{
    const std::string target = "./log.txt";
    // c_str() 函数可以将 const string* 类型 转化为 const char* 类型
    // 因为在c语言中没有string类型,必须通过string类对象的成员函数 c_str() 把 string 转换成c中的字符串样式
    FILE *fp = fopen(target.c_str(), "a+");
    if (!fp)
    {
        std::cerr << "fopen err" << std::endl;
        return;
    }
    fputs(message.c_str(), fp);

    fputs("\n", fp);
    fclose(fp);
}


信号量

1、先发现我们之前写的代码不足的地方。



// 加锁
        pthread_mutex_lock(&_mutex);

        while (is_full()) // 如果队列中满的条件满足了,就不能生产了
        {

            pthread_cond_wait(&_pcond, &_mutex); // 因为我们的生产条件不满足,无法生产,我们的生产者进行等待
        }

       
        _q.push(in);


        pthread_cond_signal(&_ccond); // 这里可以有一定的策略(比如高于多少数据再消费等等)
        
        // 解锁
        pthread_mutex_unlock(&_mutex);

 关于临界资源

1.一个线程,在操作临界资源的时候,必须临界资源是满足条件的!
2.可是,公共资源是否满足生产或者消费条件,我们无法直接得知【我们不能事前得知【在没有访问之前,无法得知】】
3.只能先加锁,再检测(while),再操作,再解锁。

因为你要检测,本质:也是在访问临界资源!

总结

因为我们在操作临界资源的时候,有可能不就绪,但是,我们无法提前得知,所以,只能先加锁,再检测,根据检测结果,决定下一步怎么走!

只要我们对资源进行整体加锁,就默认了,我们对这个资源整体使用。

实际情况可能存在:
一份公共资源,但是允许同时访问不同的区域!

无论谁想访问这一份公共资源 -- 必须先申请信号量!
只要申请信号量成功,那么就一定保证会有一个位置为你预留。

程序员编码保证不同的线程可以并发访问公共资源的不同区域!

信号量的概念

a.信号量本质是一把计数器 -- 衡量临界资源中资源数量多少的计数器


b.只要拥有信号量,就在未来一定能够拥有临界资源的一部分。

申请信号量的本质

对临界资源中特定小块资源的  预订机制 -> 有可能,我们在访问真正的临界资源之前,我们其实就可以提前知道临界资源的使用情况!!!

申请信号量的情况

只要申请成功,就一定有你的资源。
只要申请失败,就说明条件不就绪,你只能等!!

因此在申请资源之前就不需要在判断了!!!

由于多个线程要访问临界资源中的某一区域,多个线程必须得先看到信号量,那么可以推断出,信号量本身必须是公共资源。

信号量作为计数器的操作

sem --;  --- 申请资源 --- 必须保证操作的原子性  --  P


sem ++;  --- 归还资源 --- 必须保证操作的原子性 -- V

信号量核心操作: PV原语(原是原子性,语是语句)

信号量相关函数

初始化信号量

#include <semaphore.h>
int sem_init(sem_t *sem, int pshared, unsigned int value);

参数:

pshared:0表示线程间共享,非零表示进程间共享
value:信号量初始值

销毁信号量

int sem_destroy(sem_t *sem);


等待信号量

功能:

等待信号量,会将信号量的值减1

int sem_wait(sem_t *sem); //P()


发布信号量

功能:

发布信号量,表示资源使用完毕,可以归还资源了。将信号量值加1。

int sem_post(sem_t *sem);// V()

基于RingQueue的生产者消费者模型

引入环形队列

 生产和消费在什么情况下可能访问同一个位置

1.空的时候
2.满的时候
3.其他情况,生产者和消费者,根本访问的就是不同的区域!

 举个例子

把生产者和消费者比作两个小朋友在这个循环队列里面放苹果和拿苹果,一个小朋友只放苹果,一个小朋友只拿苹果。

当然,倘若盘子里面没苹果了,拿苹果那个小朋友肯定不能再拿了,除了让放苹果的小朋友进行放苹果。

倘若这个循环队列里面苹果放满了,放苹果的小朋友肯定不能再放了,除了让拿苹果的小朋友进行拿。

循环队列里面中盘子的情况 

 a.盘子全为空
两个小朋友站在一起:让谁先运行呢?(生产者)

b.盘子上全都是苹果(满)
我们两个站在一起:让谁先运行呢?(消费者)

c.其他情况,两个小朋友在的是不同的位置!

在环形队列中,大部分情况下,单生产和单消费是可以并发执行的!只有在满,或者空的时候,才有互斥和同步问题!!  

为了完成唤醒队列cp问题,我们要做的核心工作是什么?

1.你不能超过我
2.我不能把你套一个圈以上
3.我们两个什么情况会在一起


信号量是用来衡量临界资源中资源数量的

1.对于生产者而言,看中的是什么?

队列中的剩余空间 --- 空间资源定义一个信号量

2.对于消费者而言,看中的是什么?

放入队列中的数据!--- 数据资源定义一个信号量

生产者而言

prodocter_sem:10

// 申请成功,你就可以继续向下运行
// 申请失败,当前执行流,阻塞在申请处
P(producter_sem);


// 从事生产活动 -- 把数据放入到队列中

V(comsumer_sem); 

消费者而言

comsumer_sem: 0


P(comsumer_sem);

// 从事消费活动


V(producter_sem);

总结 

为满的时候,生产和消费同时到来

1、生产者无法到临界区来,因为它申请信号量无法成功

2、生产者和消费者同时来的时候,一定能保证消费者先消费


未来,生产和消费的位置我们要想清楚

1.其实就是队列中的下标
2.一定是两个下标(生产者一个下标,消费者一个下标,他们互不影响)
3.为空或者为满,下标相同

环形队列的实现(代码)

代码包含main.cc RingQueue.hpp Task.hpp  (里面有详细注释)

// main.cc 
#include "RingQueue.hpp"
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>
#include <cstdlib>
#include <ctime>
#include "Task.hpp"

std::string SelfName()
{
    char name[128];
    snprintf(name, sizeof(name), "thread[0x%x]", pthread_self());
    return name;
}

void *ProductorRoutine(void *rq)
{
    RingQueue<Task> *ringqueue = static_cast<RingQueue<Task> *>(rq);

    while (true)
    {
        // // sleep(3);
        // // version1
        // int data = rand() % 10 + 1;
        // ringqueue->Push(data);
        // std::cout << "生产完成,生产的数据是:" << data << std::endl;
        // // sleep(1);

        // version2
        // 构建or获取一个任务
        int x = rand() % 20;

        int y = rand() % 10;

        char op = oper[rand() % oper.size()];
        Task t(x, y, op, mymath);// 生产是要花费时间的
        // 生产任务
        ringqueue->Push(t);
        // 输出提示
        std::cout << SelfName() << ", 生产者派发了一个任务:" << t.toTaskString() << std::endl;
        // sleep(2);
    }
}
void *ConsumerRoutine(void *rq)
{
    RingQueue<Task> *ringqueue = static_cast<RingQueue<Task> *>(rq);

    while (true)
    {
        // // version1
        // int data;
        // ringqueue->Pop(&data);
        // std::cout << "消费完成,消费的数据时:" << data << std::endl;
        // sleep(1);

        // version2
        Task t;
        // 消费任务
        ringqueue->Pop(&t);

        std::string result = t(); // 消费是要花费时间的

        std::cout << SelfName() << ", 消费者消费了一个任务:" << result << std::endl;
    }
}

int main()
{
    // 埋下随机数种子
    srand((unsigned int)time(nullptr) ^ getpid() ^ pthread_self());

    // RingQueue<int> *rq = new RingQueue<int >();
    RingQueue<Task> *rq = new RingQueue<Task>();

    // 单生产,但消费,多生产,多消费 -->
    // 只要保证,最终进入临界区的是一个生产,一个消费就行!

    // 多生产,多消费的意义?
    pthread_t p[4], c[8];

    for (int i = 0; i < 4; i++)
    {
        pthread_create(p + i, nullptr, ProductorRoutine, rq);
    }

    for (int i = 0; i < 8; i++)
    {
        pthread_create(c + i, nullptr, ConsumerRoutine, rq);
    }

    for (int i = 0; i < 4; i++)
    {
        pthread_join(p[i], nullptr);
    }

    for (int i = 0; i < 8; i++)
    {
        pthread_join(c[i], nullptr);
    }

    // pthread_create(&p, nullptr, ProductorRoutine, rq);
    // pthread_create(&c, nullptr, ConsumerRoutine, rq);

    // pthread_join(p, nullptr);
    // pthread_join(c, nullptr);

    return 0;
}

// RingQueue.hpp
#pragma once

#include <iostream>
#include <vector>
#include <cassert>
#include <semaphore.h>

static const int gcap = 5;

template <class T>
class RingQueue
{
private:
    void P(sem_t &sem)
    {
        // 等待信号量,会将信号量的值减1
        int n = sem_wait(&sem);
        assert(n == 0);
        (void)n;
    }
    void V(sem_t &sem)
    {
        // 发布信号量,表示资源使用完毕,可以归还资源了。将信号量值加1。
        int n = sem_post(&sem);
        assert(n == 0);
        (void)n;
    }

public:
    // 信号量的初始化
    RingQueue(const int &cap = gcap)
        : _queue(cap), _cap(cap)
    {
        int n = sem_init(&_spaceSem, 0, _cap);
        assert(n == 0);
        n = sem_init(&_dataSem, 0, 0);
        assert(n == 0);

        _productorStep = _consumerStep = 0;

        pthread_mutex_init(&_pmutex, nullptr);
        pthread_mutex_init(&_cmutex, nullptr);
    }

    void Push(const T &in)
    {

        // ?:先加锁,后申请信号量,还是先申请信号量,再加锁?

        // 空间资源--
        P(_spaceSem); // 申请到了空间信号量,意味着,我一定能进行正常的生产

        pthread_mutex_lock(&_pmutex);

        // 环形队列生产者下标++
        _queue[_productorStep++] = in;

        // 将下标取模一下,以防超过队列的长度
        _productorStep %= _cap;

        pthread_mutex_unlock(&_pmutex);

        // 数据资源++
        V(_dataSem);
    }

    void Pop(T *out)
    {

        // 数据资源--
        P(_dataSem); // 申请到了数据信号量,意味着,我一定能进行正常的消费

        pthread_mutex_lock(&_cmutex);
        
        // 环形队列消费者下标++
        *out = _queue[_consumerStep++];

        // 将下标取模一下,以防超过队列的长度
        _consumerStep %= _cap;

        pthread_mutex_unlock(&_cmutex);

        // 空间资源++
        V(_spaceSem);
    }

    ~RingQueue()
    {
        sem_destroy(&_spaceSem);
        sem_destroy(&_dataSem);

        // 销毁锁
        pthread_mutex_destroy(&_pmutex);
        pthread_mutex_destroy(&_cmutex);
    }

private:
    std::vector<T> _queue;
    int _cap;
    sem_t _spaceSem; // 生产者 想生产,看中的是什么资源呢? 空间资源
    sem_t _dataSem;  // 消费者 想消费, 看中的是什么资源呢? 数据资源

    int _productorStep;
    int _consumerStep;

    // 定义锁变量
    pthread_mutex_t _pmutex;
    pthread_mutex_t _cmutex;
};


// Task.hpp
#pragma once

#include <iostream>
#include <functional>
#include <string>
#include <cstdio>

const std::string oper = "+-*/%";

int mymath(int x, int y, char op)
{
    int result = 0;
    switch (op)
    {
    case '+':
        result = x + y;
        break;
    case '-':
        result = x - y;
        break;
    case '*':
        result = x * y;
        break;

    case '/':
    {
        if (y == 0)
        {
            std::cerr << "mod zero error!" << std::endl;
            result = -1;
        }
        else
            result = x / y;
    }
    break;
    case '%':
    {
        if (y == 0)
        {
            std::cerr << "mod zero error!" << std::endl;
            result = -1;
        }
        else
            result = x % y;
    }
    break;
    default:
        break;
    }

    return result;
}

// 计算数据的类
class Task
{

    using func_t = std::function<int(int, int, char)>;
    // typedef std::function<int(int, int)> func_t;

public:
    Task()
    {
    }

    Task(int x, int y, char op, func_t func)
        : _x(x), _y(y), _op(op), _callback(func)
    {
    }

    // 该函数是消费任务的打印信息
    std::string operator()()
    {
        int result = _callback(_x, _y, _op);
        char buffer[64];
        snprintf(buffer, sizeof(buffer), "%d %c %d = %d", _x, _op, _y, result);
        return buffer;
    }

    // 该函数是生产任务的打印信息

    std::string toTaskString()
    {
        char buffer[64];
        snprintf(buffer, sizeof(buffer), "%d %c %d = ?", _x, _op, _y);
        return buffer;
    }

private:
    int _x;
    int _y;
    char _op;
    func_t _callback;
};



  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

袁百万

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值