多線程條件變數應用例子 Input_manager.h InputOpr 結構體添加 進程 ID :pthread_t t_TreadID; Makefile 添加線程庫 –lpthread LDFLAGS := -lm -lfreetype -lts –lpthread g_tTSDev = ts ...
多線程條件變數應用例子
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; }