方法1使用了系统semaphore,经过封装完成了信号量的实现,
本文章为方法2,使用条件变量 + 系统互斥量mutex实现信号量semaphore,代码如下所示:
//semaphore.h
#ifndef _SEMAPHORE_2_H__
#define _SEMAPHORE_2_H__
#include <pthread.h>
using namespace std;
typedef unsigned int uint32_t;
struct internal
{
pthread_condattr_t m_condattr;
pthread_mutex_t m_mutex;
pthread_cond_t m_cond;
int m_count;
};
/// \class CSemaphore 信号量类
class CSemaphore {
private:
CSemaphore(CSemaphore const&);
CSemaphore& operator=(CSemaphore const&);
public:
/// 构造函数,创建系统信号量,initCnt表示信号量的初始计数
explicit CSemaphore(int initCnt = 0);
/// 析构函数,销毁系统信号量
~CSemaphore();
/// 消费信号量,当信号量为0时线程再消费信号量,线程就会被阻塞,进入信号量等待队列的队尾
/// \return pend操作后当前信号量计数
int pend();
/// 生产信号量,如果信号量为0时有线程生产信号量,会唤醒信号量其等待队列的第一个线程
/// \return post操作后当前信号量计数
int post();
/// 消费信号量,当信号量为0时线程再消费信号量,线程就