返回顶部

收藏

c++互斥类的一个实现

更多
/* 
 * MyMutex.h
 */

#ifndef __MYMUTEX_H__
#define __MYMUTEX_H__

#ifndef WIN32
#include <pthread.h>
#else
#include <Windows.h>
#endif

/* 动态库宏 */
#ifdef WIN32

#ifdef LOG_BUILD_DLL
# define  LOG_EXPROT _declspec(dllexport) //for windows
#else 
# define  LOG_EXPROT _declspec(dllimport) //for windows
#endif

# else
# define LOG_EXPROT  //for linux
#endif

class LOG_EXPROT LockableObject
{
public:
    LockableObject(){}
    ~LockableObject(){}

    virtual void lock() = 0;
    virtual void unlock() = 0;
};

class LOG_EXPROT MyMutex: public LockableObject
{
public:
    MyMutex();
    ~MyMutex();

    void lock();
    void unlock();

private:

#ifndef WIN32
    pthread_mutex_t  mutex_;
#else
    CRITICAL_SECTION  criticalSection_;
#endif

};

class LOG_EXPROT MyGuard
{
public:
    MyGuard(LockableObject *pLockableObject)
    {
        pLockableObject_ = pLockableObject;
        pLockableObject_->lock();
    }

    ~MyGuard()
    {
        pLockableObject_->unlock();
    }

private:
    LockableObject * pLockableObject_;
};

#endif /*__MYMUTEX_H__*/

/* MyMutex.cpp
 *
 */

#include "MyMutex.h"
#include <iostream>

MyMutex::MyMutex()
{
#ifndef WIN32
    pthread_mutex_init(&mutex_, NULL);
#else
    InitializeCriticalSection(&criticalSection_);
#endif
}

MyMutex::~MyMutex()
{
#ifndef WIN32
    int ret = pthread_mutex_destroy(&mutex_);
    if(ret)
        std::cout<<"pthread_mutex_destroy error"<<std::endl;                                    
#else
    DeleteCriticalSection(&criticalSection_);
#endif
}

void MyMutex::lock()
{
#ifndef WIN32
    int ret = pthread_mutex_lock(&mutex_);
    if (ret)
        std::cout<<"pthread_mutex_lock error"<<std::endl;                                        
#else
    EnterCriticalSection(&criticalSection_);
#endif
    return;
}

void MyMutex::unlock()
{
#ifndef WIN32
    int ret = pthread_mutex_unlock(&mutex_);
    if (ret)
        std::cout<<"pthread_mutex_unlock error"<<std::endl;
#else
    LeaveCriticalSection(&criticalSection_);
#endif
    return;
}

标签:c++,mutex

收藏

0人收藏

支持

0

反对

0

发表评论