多线程条件变量应用例子
Input_manager.h
InputOpr 结构体添加
进程 ID :pthread_t t_TreadID;
int AllInputDevicesInit(void) { PT_InputOpr ptTmp = g_ptInputOprHead; int iError = -1; while (ptTmp) { if (0 == ptTmp->DeviceInit()) { /* 创建子线程 */ pthread_create(&ptTmp->t_TreadID, NULL, InputEventThreadFunction, ptTmp->GetInputEvent); /* 最后一个参数是给 InputEventThreadFunction用的*/ iError = 0; } ptTmp = ptTmp->ptNext; } return iError; }
/* 线程函数 */ static void* InputEventThreadFunction(void *pVoid) { T_InputEvent tInputEvent; /* 定义函数指针 */ int (*GetInputEvent)(PT_InputEvent ptInputEvent); /* 让这个函数指针指向 输入参数*/ GetInputEvent = (int (*)(PT_InputEvent))pVoid; while(1) { if(0 == GetInputEvent(&tInputEvent)) { /* 有数据变化,唤醒主进程,把tInputEvent的值传给一个全局变量 */ /* 访问临界资源前先获得互斥变量 */ pthread_mutex_lock(&g_tmutex); /* 原子方法赋值 */ g_tInputEvent = tInputEvent; /* 唤醒主线程 */ pthread_cond_signal(&g_tcondvar); /* 释放互斥变量 */ pthread_mutex_unlock(&g_tmutex); } } return NULL; }
int GetInputEvent(PT_InputEvent ptInputEvent) { /* 休眠 */ pthread_mutex_lock(&g_tmutex); /* 条件等待函数 */ pthread_cond_wait(&g_tcondvar, &g_tmutex); /* 程序能够向下继续证明被唤醒啦 */ /* 被唤醒之后返回数据 */ *ptInputEvent = g_tInputEvent; pthread_mutex_unlock(&g_tmutex); return 0; }
Makefile 添加线程库 –lpthread
LDFLAGS := -lm -lfreetype -lts –lpthread
g_tTSDev = ts_open(pcTSName, 0); /* 以阻塞方式打开 */
其实就是两个输入方式都以循环方式等待有数据变化,然后唤醒主线程处理
改为滑动翻页
只需修改一个函数即可
static int TouchScreenGetInputEvent(PT_InputEvent ptInputEvent) { struct ts_sample tSamp; struct ts_sample tSampPressed; struct ts_sample tSampReleased; int iRet; int bStart = 0; int iDelta; static struct timeval tPreTime; while(1) { iRet = ts_read(g_tTSDev, &tSamp, 1); /* 如果无数据则休眠 */ if(1 == iRet) { if ((tSamp.pressure > 0) && (bStart == 0)) { tSampPressed = tSamp; bStart = 1; } if (tSamp.pressure <= 0) { tSampReleased = tSamp; //bStart = 0; /* 处理数据 */ if(!bStart) { return -1; } else { iDelta = tSampReleased.x - tSampPressed.x; ptInputEvent->tTime = tSampReleased.tv; ptInputEvent->iType = INPUT_TYPE_TOUCHSCREEN; if (iDelta > giXres/5) { /* 翻到上一页 */ ptInputEvent->iVal = INPUT_VALUE_UP; } else if (iDelta < 0 - giXres/5) { /* 翻到下一页 */ ptInputEvent->iVal = INPUT_VALUE_DOWN; } else { ptInputEvent->iVal = INPUT_VALUE_UNKNOWN; } return 0; } } } else { return -1; } } return 0; }