📄 myevent_linux.c
字号:
/*
*
*myevent_linux.c 条件(cond)/事件(event) lin shao chuan
*
*/
#include "myevent.h"
#include <pthread.h>
#include <errno.h>
#include <sys/time.h>
#include "mylog.h"
typedef struct __myevent_t_
{
HMYMEMPOOL hm;
pthread_cond_t cond;
pthread_mutex_t mtx;
}myevent_t;
/*
*
*创建事件/条件
*
*/
HMYEVENT MyEventRealConstruct(HMYMEMPOOL hm, int bNotAutoReset)
{
int ret = 0;
int ret1 = 0;
myevent_t * me = (myevent_t *)MyMemPoolMalloc(hm, sizeof(*me));
if(NULL == me)
return NULL;
me->hm = hm;
ret = pthread_cond_init(&me->cond, NULL);
ret1 = pthread_mutex_init(&me->mtx, NULL);
if(0 != ret || 0 != ret1)
{
LOG_WARN(("fail create event"));
MyMemPoolFree(hm, me);
return NULL;
}
return (HMYEVENT)me;
}
/*
*
*销毁事件/条件
*
*/
void MyEventDestruct(HMYEVENT he)
{
struct timespec abstime = {0};
myevent_t * me = (myevent_t *)he;
if(NULL == me)
return;
if(ETIMEDOUT == pthread_cond_timedwait(&me->cond, &me->mtx, &abstime))
pthread_cond_signal(&me->cond);
pthread_cond_destroy(&me->cond);
pthread_mutex_destroy(&me->mtx);
MyMemPoolFree(me->hm, me);
}
/*
*
*把事件设置成signaled状态
*
*/
void MyEventSetSignaled(HMYEVENT he)
{
myevent_t * me = (myevent_t *)he;
if(NULL == me)
return;
pthread_cond_signal(&me->cond);
}
/*
*
*把事件设置成非signaled状态
*
*/
void MyEventSetNoSignaled(HMYEVENT he)
{}
/*
*
* 等待事件发生,
*
*param millsecond:单位毫秒, -1表示无限等待,直至事件发生
*/
int MyEventWait(HMYEVENT he, struct timeval * timeout)
{
myevent_t * me = (myevent_t *)he;
if(NULL == me)
return -1;
if(NULL == timeout)
return pthread_cond_wait(&me->cond, &me->mtx);
else
{
struct timespec abstime = {0};
struct timeval now = {0};
gettimeofday(&now, NULL);
abstime.tv_nsec = (now.tv_usec + timeout->tv_usec) * 1000;
abstime.tv_sec = now.tv_sec + timeout->tv_sec;
if(abstime.tv_nsec > 1000 * 1000 * 1000)
{
abstime.tv_sec += 1;
abstime.tv_nsec = abstime.tv_nsec % (1000 * 1000 * 1000);
}
return pthread_cond_timedwait(&me->cond, &me->mtx,
&abstime);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -