⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 myevent_pipe.c

📁 提供了rbtree ttree avltree list hashtable等常用容器的算法,代码经过uclinux + arm44b0平台验证
💻 C
字号:
/*
*
*myevent_pipe.c 利用select pipe实现一个事件封装
*
*/


#include "myevent.h"

#include <pthread.h>
#include <errno.h>
#include <sys/time.h>

#include "mypipe.h"
#include "mymutex.h"
#include "mylog.h"


typedef struct __myevent_t_
{
	HMYMEMPOOL hm;

	/*
	* 是否有线程在等待当前的信号
	*/
	int bThrWait;
	
	/*
	* bThrWait的保护锁
	*/
	HMYMUTEX protecter;
	
	/*
	* 做为信号使用的管道
	*/
	HMYPIPE hpipeEvent;	
}myevent_t;


static void destroy(myevent_t * me)
{
	if(NULL == me)
		return;

	MyMutexLock(me->protecter);
	if(me->bThrWait)
		MyPipeWrite(me->hpipeEvent, "1", strlen("1"));
	MyMutexUnLock(me->protecter);

	MyPipeDestruct(me->hpipeEvent);

	MyMutexDestruct(me->protecter);

	MyMemPoolFree(me->hm, me);
}


/*
*
*创建事件/条件
*
*/
HMYEVENT MyEventRealConstruct(HMYMEMPOOL hm, int bNotAutoReset)
{
	myevent_t * me = (myevent_t *)MyMemPoolMalloc(hm, sizeof(*me));
	if(NULL == me)
		return NULL;

	me->bThrWait = 0;
	me->hm = hm;
	me->protecter = MyMutexConstruct(me->hm);
	me->hpipeEvent = MyPipeConstruct(me->hm);
	
	if(NULL == me->protecter || NULL == me->hpipeEvent)
	{
		LOG_WARN(("fail create event"));

		destroy(me);
		
		return NULL;
	}

	return (HMYEVENT)me;	
}

/*
*
*销毁事件/条件
*
*/
void MyEventDestruct(HMYEVENT he)
{
	myevent_t * me = (myevent_t *)he;
	if(NULL == me)
		return;

	destroy(me);
}

/*
*
*把事件设置成signaled状态
*
*/
void MyEventSetSignaled(HMYEVENT he)
{
	char a[1] = {0};

	myevent_t * me = (myevent_t *)he;
	if(NULL == me)
		return;

	MyPipeWrite(me->hpipeEvent, a, sizeof(a));
}

/*
*
*把事件设置成非signaled状态
*
*/
void MyEventSetNoSignaled(HMYEVENT he){}

/*
*
* 等待事件发生, 
*
*param millsecond:单位毫秒, -1表示无限等待,直至事件发生
*/
int MyEventWait(HMYEVENT he, struct timeval * timeout)
{
	char a[1];
	fd_set read_mask;

	myevent_t * me = (myevent_t *)he;
	if(NULL == me)
		return -1;

	/* 加锁 */
	MyMutexLock(me->protecter);

	if(me->bThrWait)
	{
		/* 解锁 */
		MyMutexUnLock(me->protecter);

		return -1;
	}

	me->bThrWait = 1;
	
	/* 解锁 */
	MyMutexUnLock(me->protecter);

	FD_ZERO(&read_mask);
	FD_SET(MyPipeGetReadFD(me->hpipeEvent), &read_mask);

	select(MyPipeGetReadFD(me->hpipeEvent) + 1, &read_mask, NULL, NULL, timeout);

	if(FD_ISSET(MyPipeGetReadFD(me->hpipeEvent), &read_mask))
		MyPipeRead(me->hpipeEvent, a, sizeof(a));

	/* 加锁 */
	MyMutexLock(me->protecter);

	me->bThrWait = 0;

	/* 解锁 */
	MyMutexUnLock(me->protecter);
	
	return 0;
}
















⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -