线程类封装(4)
来源:互联网 发布:查看淘宝宝贝类目 编辑:程序博客网 时间:2024/06/06 04:16
#ifndef THREAD_EVENT_H_
#define THREAD_EVENT_H_
// #include <standard C library headers>
#include <time.h>
// #include <standard C++ library headers>
// #include <other library headers>
#ifdef _WIN32
#include <Windows.h>
#else
#include <pthread.h>
#include <sys/time.h>
#endif
// #include "custom headers"
namespace thread
{
class Event
{
public:
Event();
/*virtual*/ ~Event();
private:
Event(const Event& rhs);
Event& operator=(const Event& rhs);
public:
void NotifyAll();
void Wait();
bool Wait(int ms);
protected:
private:
#ifdef _WIN32
HANDLE event;
#else
pthread_cond_t cond;
pthread_mutex_t mutex;
#endif
};
#ifdef _WIN32
inline Event::Event()
{
event = ::CreateEvent(NULL, TRUE, FALSE, NULL);
}
inline Event::~Event()
{
::CloseHandle(event);
}
inline void Event::NotifyAll()
{
::PulseEvent(event);
}
inline void Event::Wait()
{
::WaitForSingleObject(event, INFINITE);
}
inline bool Event::Wait(int ms)
{
return (::WaitForSingleObject(event, ms) == WAIT_OBJECT_0);
}
#else
inline Event::Event()
{
pthread_cond_init(&cond, NULL);
pthread_mutex_init(&mutex, NULL);
}
inline Event::~Event()
{
pthread_cond_destroy(&cond);
pthread_mutex_destroy(&mutex);
}
inline void Event::NotifyAll()
{
pthread_cond_broadcast(&cond);
}
inline void Event::Wait()
{
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond, &mutex);
pthread_mutex_unlock(&mutex);
}
inline bool Event::Wait(int ms)
{
struct timespec ts;
struct timeval tv;
gettimeofday(&tv, NULL);
ts.tv_sec = tv.tv_sec + (ms / 1000);
ts.tv_nsec = tv.tv_usec * 1000 + ((ms % 1000) * 1000 * 1000);
// clock_gettime(CLOCK_REALTIME, &ts);
// ts.tv_sec += (ms / 1000);
// ts.tv_nsec += ((ms % 1000) * 1000 * 1000);
pthread_mutex_lock(&mutex);
bool ret = (pthread_cond_timedwait(&cond, &mutex, &ts) == 0);
pthread_mutex_unlock(&mutex);
return ret;
}
#endif // _WIN32
} // namespace thread
#endif // EVENT_H_
- 线程类封装(4)
- 线程类封装(1)
- 线程类封装(2)
- 线程类封装(3)
- 线程类封装(5)
- 一个线程封装类
- C++封装线程类
- 线程类基本封装
- 类封装线程(动态线程)
- 线程控制 - AfxBeginThreadUI线程的封装类
- 封装的线程注入类
- 封装线程类的方法
- 线程局部变量封装类
- linux 线程池类封装
- 线程封装类(1)
- 线程封装类(2)
- 线程入口地址 类封装
- 封装一个Window线程类
- 软件架构
- 线程类封装(2)
- 一名25岁的董事长给大学生的忠告
- 线程类封装(3)
- 流程图
- 线程类封装(4)
- 线程类封装(5)
- 系统架构师是怎样炼成的
- Socket封装
- 架构规范
- perl 实现的基本排序算法
- Socket封装2
- c#交友哦
- 窗体与窗体的数据传送