C++ 互斥量的封装

来源:互联网 发布:各种排序算法 编辑:程序博客网 时间:2024/06/06 05:11

贡献自己写的部分代码,希望能帮助到有需要的人。


代码可以在Windows/Linux下运行,可以作为一个基础类。


头文件

mutex.h

#ifndef MUTEX_H#define MUTEX_H#ifdef WIN32typedef void* HANDLE;#else#include <pthread.h>#endifclass Mutex{public:    Mutex(void);    ~Mutex(void);    void lock(void);    void unlock(void);#ifdef WIN32    HANDLE m_handle;#else    pthread_mutex_t m_handle;#endif};#endif


源文件

mutex.cpp

#ifdef WIN32#include <Windows.h>#endif#include "mutex.h"Mutex::Mutex(void){#ifdef WIN32    m_handle = ::CreateMutexA(NULL, FALSE, NULL);#else    pthread_mutex_init(&m_handle, NULL);#endif}Mutex::~Mutex(void){#ifdef WIN32    ::CloseHandle(m_handle);#else    pthread_mutex_destroy(&m_handle);#endif}void Mutex::lock(void){#ifdef WIN32    WaitForSingleObject(m_handle, INFINITE);#else    pthread_mutex_lock(&m_handle);#endif}void Mutex::unlock(void){#ifdef WIN32    ::ReleaseMutex(m_handle);#else    pthread_mutex_unlock(&m_handle);#endif}



原创粉丝点击