cond + mutex 最早用的,线程abc执行当满足条件时,否则竞争测试条件满足否。
void printNumber(int x) { printf("%d", x); return; } typedef struct { int n; } ZeroEvenOdd; ZeroEvenOdd* zeroEvenOddCreate(int n) { ZeroEvenOdd* obj = (ZeroEvenOdd*) malloc(sizeof(ZeroEvenOdd)); obj->n = n; return obj; } int g_iCurIndex = -1; pthread_mutex_t g_tMutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t g_tCond = PTHREAD_COND_INITIALIZER; void zero(ZeroEvenOdd* obj) { int iRet = 0; while (1) { iRet = pthread_mutex_lock(&g_tMutex); if (iRet) continue; while (g_iCurIndex % 2 != 0) { pthread_cond_wait(&g_tCond, &g_tMutex); } if (g_iCurIndex == obj->n * 2) { g_iCurIndex = 0; pthread_cond_broadcast(&g_tCond); pthread_mutex_unlock(&g_tMutex); /* free obj */ zeroEvenOddFree(obj); break; } printNumber(0); g_iCurIndex++; pthread_mutex_unlock(&g_tMutex); pthread_cond_broadcast(&g_tCond); } pthread_exit(NULL); } void odd(ZeroEvenOdd* obj) { int iRet = 0; while (1) { iRet = pthread_mutex_lock(&g_tMutex); if (iRet) continue; while ((g_iCurIndex % 2 == 0) || (g_iCurIndex % 4 != 1)) { pthread_cond_wait(&g_tCond, &g_tMutex); } iRet = g_iCurIndex; printNumber((iRet + 1) / 2); g_iCurIndex++; pthread_mutex_unlock(&g_tMutex); pthread_cond_broadcast(&g_tCond); if (iRet + 4 > obj->n * 2) break; } pthread_exit(NULL); } void even(ZeroEvenOdd* obj) { int iRet = 0; while (iRet = pthread_mutex_lock(&g_tMutex) != 0); g_iCurIndex = 0; pthread_mutex_unlock(&g_tMutex); while (1) { iRet = pthread_mutex_lock(&g_tMutex); if (iRet) continue; while ((g_iCurIndex % 2 == 0) || (g_iCurIndex % 4 != 3)) { pthread_cond_wait(&g_tCond, &g_tMutex); if (g_iCurIndex == 0) { pthread_exit(NULL); } } printNumber((g_iCurIndex + 1 ) / 2); iRet = g_iCurIndex; g_iCurIndex++; pthread_mutex_unlock(&g_tMutex); pthread_cond_broadcast(&g_tCond); if (iRet + 4 > obj->n * 2) break; } pthread_exit(NULL); } void zeroEvenOddFree(ZeroEvenOdd* obj) { if (obj) { free(obj); obj = NULL; } return; }