贡献自己写的部分代码,希望能帮助到有需要的人。
代码可以在Windows/Linux下运行,可以作为一个基础类。
头文件
mutex.h
#ifndef MUTEX_H
#define MUTEX_H
#ifdef WIN32
typedef void* HANDLE;
#else
#include <pthread.h>
#endif
class 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
}