资源简介
C++封装实现的异步加锁消息队列,支持多线程,完美封装,可用于消息接收、处理
代码片段和文件信息
#include “Synchronized.h“
Synchronized::Synchronized(void)
{
#ifdef WIN32
// Semaphore initially auto signaled auto reset mode unamed
event_ = CreateEvent(0 false false 0);
// Semaphore initially unowed unamed
mutex_ = CreateMutex(0 false 0);
locked_ = false;
notifies_ = 0;
#else
memset(&mutex_ 0 sizeof(mutex_));
int result = pthread_mutex_init(&monitor 0);
if (result)
{
throw std::runtime_error(“Synchronized mutex_init failed!“);
}
memset(&cond_ 0 sizeof(cond_));
result = pthread_cond_init(&cond_ 0);
if (result)
{
throw std::runtime_error(“Synchronized cond_init failed!“);
}
#endif
}
Synchronized::~Synchronized(void)
{
#ifdef WIN32
CloseHandle(event_);
CloseHandle(mutex_);
#else
pthread_cond_destroy(&cond_);
pthread_mutex_destroy(&mutex_);
#endif
}
void Synchronized::Wait()
{
#ifdef WIN32
Wait(INFINITE);
#else
cond_timed_wait(0);
#endif
}
#ifndef WIN32
int Synchronized::cond_timed_wait(const timespec *timeout)
{
int result = 0;
if (timeout)
{
result = std::pthread_cond_timedwait(&cond_ &mutex_ timeout);
}
else
{
result = std::pthread_cond_wait(&cond_ &mutex_);
}
return result;
}
#endif
bool Synchronized::Wait(unsigned long timeout)
{
bool timeout_occurred = false;
#ifdef WIN32
locked_ = false;
if (!ReleaseMutex(mutex_))
{
throw std::runtime_error(“Synchronized: releasing mutex failed“);
}
int error = WaitForSingleobject(event_ timeout);
switch(error)
{
case WAIT_TIMEOUT:
timeout_occurred = true;
break;
case WAIT_ABANDONED:
throw std::runtime_error(“Synchronized: waiting for event failed“);
timeout_occurred = false;
break;
default:
break;
}
if (WAIT_object_0 != WaitForSingleobject(mutex_ INFINITE))
{
throw std::runtime_error(“Synchronized: waiting for mutex failed“);
}
locked_ = true;
#else
struct timespec ts;
struct timeval tv;
gettimeofday(&tv 0);
ts.tv_sec = tv.tv_sec + (int)timeout / 1000;
ts.tv_nsec = (tv.tv_usec + (timeout % 1000) * 1000) * 1000;
int error = cond_timed_wait(&ts);
if (error > 0)
{
switch(error)
{
case ETIMEDOUT:
timeout_occurred = true;
break;
default:
throw std::runtime_error(“Synchronized: wait with timeout returned!“);
break;
}
}
#endif
return timeout_occurred;
}
void Synchronized::Notify()
{
#ifdef WIN32
notifies_ = 1;
if (!SetEvent(event_))
{
throw std::runtime_error(“Synchronized: notify failed!“);
}
#else
int result = pthread_cond_signal(&cond_);
if (result)
{
throw std::runtime_error(“Synchronized: notify failed!“);
}
#endif
}
void Synchronized::NotifyAll()
{
#ifdef WIN32
notifies_ = (char)0x80;
while (notifies_--)
{
if (!SetEvent(event_))
{
throw std::runtime_error(“Synchronized: notify all failed!“);
}
}
#else
int result = pthread_cond_broadcast(&cond_);
if (result)
{
throw std::runtime_
属性 大小 日期 时间 名称
----------- --------- ---------- ----- ----
文件 4406 2017-11-22 09:18 Synchronized.cpp
文件 1485 2017-11-22 09:18 Synchronized.h
文件 1438 2017-11-22 09:18 SyncQueue.h
- 上一篇:矩阵的qr分解,特征值计算,谱分解
- 下一篇:求两点之间所有路径的C++代码
评论
共有 条评论