1.在多线程后端程序中,我们经常需要等待休眠,如下是自己封装等待休眠的API.
#ifndef __CIDLE__H_
#define __CIDLE__H_
#include "common.h"
class CIdle
{
public:
CIdle();
~CIdle();
public:
void Sleep(unsigned long iTime = 500);
void Activate();
private:
#if defined(WIN32) || defined(_WIN32)
HANDLE mHandle;
#elif __linux__
pthread_cond_t mhCondition;
#endif
};
#endif
#include "Idle.h"
#include "CMutex.h"
CIdle::CIdle()
{
#if defined(WIN32) || defined(_WIN32)
mHandle = CreateEvent(nullptr, FALSE, FALSE, nullptr);
#elif __linux__
pthread_condattr_t cond_attr;
pthread_condattr_init(&cond_attr);
pthread_cond_init(&mhCondition, &cond_attr);
pthread_condattr_destroy(&cond_attr);
#endif
}
CIdle::~CIdle()
{
#if defined(WIN32) || defined(_WIN32)
if (nullptr != mHandle)
{
CloseHandle(mHandle);
}
#elif __linux__
pthread_cond_destroy(&mhCondition);
#endif
}
void CIdle::Sleep(unsigned long iTime)
{
#if defined(WIN32) || defined(_WIN32)
if (nullptr != mHandle)
{
WaitForSingleObject(mHandle, iTime);
}
#elif __linux__
if(mhCondition.__data.__total_seq != -1ULL)
{
CMutex cTemp;
cTemp.Lock();
timespec ts;
struct timeval tv;
gettimeofday(&tv, nullptr);
int64_t usec = tv.tv_usec + iTime * 1000LL;
ts.tv_sec = tv.tv_sec + usec / 1000000;
ts.tv_nsec = (usec % 1000000) * 1000;
pthread_cond_timedwait(&mhCondition, cTemp.GetMutex(), &ts);
cTemp.UnLock();
}
#endif
}
void CIdle::Activate()
{
#if defined(WIN32) || defined(_WIN32)
if (nullptr != mHandle)
{
SetEvent(mHandle);
}
#elif __linux__
if (mhCondition.__data.__total_seq != -1ULL)
{
pthread_cond_signal(&mhCondition);
}
#endif
}