muduo源码解析6-condtion类

condition

class condition:noncopyable
{
};

作用:

实现了最简单condtion操作,包括init,destroy,wait,notify,notifyAll,waitforseconds操作,
内部数据也很简单,mutexlock& m_mutex和pthread_cond_t m_cond
使用方法和std::cond一样

成员变量:

private:
    mutexlock& m_mutex;
    pthread_cond_t m_cond;

成员函数:

public:
    explicit condition(mutexlock& mutex):m_mutex(mutex)
    {
        pthread_cond_init(&m_cond,NULL);
    }
    ~condition()
    {
        pthread_cond_destroy(&m_cond);
    }
    //不满足条件时wait,把mutexlock中m_holder移除,同时该线程释放该锁
    void wait()
    {
        mutexlock::UnassignGuard ug(m_mutex);
        pthread_cond_wait(&m_cond,m_mutex.getPthreadMutex());
    }

    //等待一段时间而不是一直等待
    bool waitForSeconds(double seconds);

    //唤醒cond阻塞队列中的第一个线程
    void notify()
    {
        pthread_cond_signal(&m_cond);
    }

    //唤醒cond阻塞队列中的所有线程
    void notifyAll()
    {
        pthread_cond_broadcast(&m_cond);
    }

测试:

使用condtion和mutex完成一个生产者消费者同步的小例子。

#include"base/mutex.h"
#include"base/condition.h"
#include<thread>
#include <stdio.h>
#include<queue>
#include<iostream>

#define MAXQUEUE 5
mymuduo::mutexlock mutex;
mymuduo::condition cond(mutex);
std::queue<int> task_queue;

namespace mymuduo{
namespace currentthread {

void cacheTid()
{
}
}
}

void provider()
{
    while(1)
    {
    std::this_thread::sleep_for(std::chrono::milliseconds(2));
    mymuduo::mutexlockguard mlg(mutex);
    while(task_queue.size()>=MAXQUEUE)
        cond.wait();
    task_queue.push(rand()%1000);
    std::cout<<"push "<<task_queue.front()<<std::endl;
    cond.notifyAll();
    }
}

void consumer()
{
    while(1)
    {
    mymuduo::mutexlockguard mlg(mutex);
    while(task_queue.empty())
        cond.wait();
    std::cout<<"pop "<<task_queue.front()<<std::endl;
    task_queue.pop();
    cond.notifyAll();
    }
}

int main()
{
  std::thread t[2];
  t[0]=std::thread(provider);
  t[1]=std::thread(consumer);

  t[0].join();t[1].join();
}

 

posted @ 2020-08-23 00:51  WoodInEast  阅读(170)  评论(0编辑  收藏  举报