返回顶部

收藏

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

相关聚客文章
  1. 博主 发表 2013-04-17 09:20:01 C++11 mutex方便的自解锁lock_guard
  2. Boris Kolpackov 发表 2012-11-22 12:15:22 ODB 2.1.1 Released
  3. shakuner 发表 2013-04-01 07:59:16 C++中虚函数的作用是什么?它应该怎么用呢?
  4. learnhard 发表 2013-05-04 16:58:05 [原创]VC++连接/操作MySQL数据库(通过MySQL C API)
  5. Qiang 发表 2012-06-06 11:26:00 程序如何找自己
  6. Brad Sullivan 发表 2013-06-26 15:00:00 Just My Code for C++ in VS 2013
  7. Leo 发表 2013-07-21 13:16:33 C语言全局变量那些事儿
  8. 刘 凡超 发表 2013-01-14 16:14:00 WebKit/WTF中的RefPtr
  9. Solstice 发表 2013-10-09 07:50:21 C++11的Lambda使用一例:华容道求解
  10. maipianshuo 发表 2013-11-16 04:22:53 [C++技巧篇2]C++11中的RAII
  11. Raman Sharma 发表 2013-12-21 03:21:00 Asynchronous programming in C++ using resumable fu
  12. Conda 发表 2014-03-01 07:50:07 C++ 字符分割解决办法

发表评论