C++:互斥量C++实现,内存调试,自动锁

 

/*互斥量C++实现+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/

class CMutex
{
public:
    CMutex() ;
    ~CMutex() ;

    void lock() ;
    void unlock() ;

private:

#ifdef _WIN32
    CRITICAL_SECTION cs;
#else
    pthread_mutex_t cs;
    pthread_mutexattr_t mta ;
#endif
};

#ifdef _WIN32
CMutex::CMutex()
{
    InitializeCriticalSection(&cs);
}

CMutex::~CMutex()
{
    DeleteCriticalSection(&cs);
}

void CMutex::lock()
{
    EnterCriticalSection(&cs);
}

void CMutex::unlock()
{
    LeaveCriticalSection(&cs);
}
#else
CMutex::CMutex()
{
    pthread_mutexattr_init( &mta ) ;
    pthread_mutexattr_settype( &mta , PTHREAD_MUTEX_RECURSIVE_NP ) ;
    pthread_mutex_init( &cs , &mta ) ;
}

CMutex::~CMutex()
{
    pthread_mutexattr_destroy( &mta ) ;
    pthread_mutex_destroy(&cs);
}

void CMutex::lock()
{
    //printf( " lock the %d \r\n" , &cs ) ;
    pthread_mutex_lock(&cs);
}

void CMutex::unlock()
{
    //printf( " unlock the %d \r\n" , &cs ) ;
    pthread_mutex_unlock(&cs);
}
#endif

/* 例一 内存调试+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
//如果定义了内存调试宏
#ifdef DEBUG_MALLOC
CMutex    mallocMutex ;
int        malloctick = 0 ;

//-----------------------------------------------
//对内存分配增加一个计数器,用于调试内存泄露
void *debugMalloc( int size )
{
    void *pmem = 0 ;
    mallocMutex.lock() ;

    //malloc次数+1
    malloctick ++ ;
    pmem = malloc( size ) ;

    printf( "debugMalloc count = %d\r\n" , malloctick ) ;

    mallocMutex.unlock() ;

    return pmem ;
}

//-----------------------------------------------
//用于调试内存泄露
void    debugFree( void *pmem )
{
    mallocMutex.lock() ;
    //malloc次数-1
    malloctick -- ;
    free( pmem ) ;
    printf( "debugFree count = %d\r\n" , malloctick ) ;
    mallocMutex.unlock() ;
}
#endif    //DEBUG_MALLOC

/* 例二 自动锁+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/*自动锁作用在一个局部,在函数内部,从声明该锁开始,到函数退出时,销毁自动锁时,在析构函数里面调用CMutex::unlock()*/
class CAutoMutex
{
public:
    CAutoMutex( CMutex *mutex )
    {
        m_pmutex = mutex ;
        if( m_pmutex )
            m_pmutex->lock() ;
    }

    virtual ~CAutoMutex()
    {
        if( m_pmutex )
        {
            m_pmutex->unlock() ;
            m_pmutex = NULL ;
        }
    };
private:
    CMutex                *m_pmutex ;
};

//一个使用自动锁的类
class CNetServer
{
protected:
    CNetServer() ;
    ~CNetServer() ;
    DECLARE_SINGLEOBJ( CNetServer )
publicbool            RequestTalkOn( unsigned userid );
protected:
    //对讲标志状态
    bool            m_talkOn ;
    int                m_talkUserID ;
    CMutex            m_taklMutex ;
};

//使用示例
bool CNetServer::RequestTalkOn( unsigned userid )
{
    CAutoMutex atlck( &m_taklMutex);
    m_talkUserID = userid ;
    m_talkOn = true ;
    NETLIB_PRINTF("request Talkon success userid = %d\r\n" , userid ) ;
    return true ;
}
/*THE END, ocj*/

 

posted @ 2016-03-15 16:01  oucaijun  阅读(1563)  评论(0编辑  收藏  举报
下载TeamViewer完整版 下载TeamViewer