C++互斥锁与条件变量的封装使用

来源:互联网 发布:网络问诊 编辑:程序博客网 时间:2024/05/24 06:53

互斥锁类的封装:

#ifndef _MUTEXLOCK_H#define _MUTEXLOCK_H#include <pthread.h>#include <assert.h>class MutexLock{    friend class Condition; //将条件变量设为友元类,访问MutexLock私有成员private:    pthread_mutex_t _mutex;    bool _isLocking;    void restoreMutexStatus()//条件变量使用    {        _isLocking = true;    }public:    MutexLock() : _isLocking(false)    {        pthread_mutex_init(&_mutex, NULL); //初始化互斥量    }    ~MutexLock()    {        assert(!_isLocking()); //确保已解锁        pthread_mutex_destory(&_mutex);    //摧毁互斥量    }    void lock()    {        pthread_mutex_lock(&_mutex);    //加锁并将锁状态设为true        _isLocking = true;    }    void unlock()    {        pthread_mutex_unlock(&_mutex);  //解锁并将锁状态设为false        _isLocking = false;    }    bool isLocking() const            //获取锁状态    {        return _isLocking;            }    pthread_mutex_t* getMutexPtr()    //获取锁    {        return &_mutex;    }};//--------------------------------------------------------//守护锁类class MutexLockGuard{public:    MutexLockGuard(MutexLock& mutex) :_mutex(mutex) //构造函数加锁    {        _mutex.lock();    }    ~MutexLockGuard()     //析构函数解锁    {        _mutex.unlock();    }private:    MutexLock& _mutex;};#endif

条件变量类的封装:

#ifndef _CONDITION_H#define _CONDITION_H#include <pthread.h>class MutexLock;class Condition{public:    Condition(MutexLock& mutex) : _mutex(mutex)    {        pthread_cond_init(&_cond, NULL);    }    ~Condition()    {        pthread_cond_destory(&_cond);    }    void wait()    {        assert(_mutex.isLocking());//必须为上锁状态        pthread_cond_wait(&_cond, _mutex.getMutexPtr());        _mutex.restoreMutexStatus();//还原锁的状态    }    void notify()    {        pthread_cond_signal(&_cond);    }    void notifyAll()    {        pthread_cond_broadcast(&_cond);    }private:    pthread_cond_t _cond;    MutexLock& _mutex;};#endif
0 0