常用信号量API #ifdef WIN32 typedef void wsemaphore; #else typedef struct pthread_semaphore_t { pthread_cond_t cond; pthread_mutex_t mutex; int nitems; }wsemaphore; #endif //创建信号量 wsemaphore *create_semaphore(int initial) { #ifdef WIN32 //initial 初始量 ,1000000 最大值 return(CreateSemaphore(NULL, initial, 1000000, NULL)); #else wsemaphore *sem; sem = new wsemaphore; if (sem == (wsemaphore *)NULL) return ((wsemaphore *)NULL); if(pthread_mutex_init(&(sem->mutex), NULL)) { delete sem; return((wsemaphore *)NULL); } if(pthread_cond_init(&(sem->cond), NULL)) { delete sem; return((wsemaphore *)NULL); } sem->nitems = initial; return sem; #endif } //信号量 -1 int acquire_semaphore(wsemaphore *psemaphore) { #ifdef WIN32 return (WaitForSingleObject(psemaphore, INFINITE)); #else pthread_mutex_lock(&(psemaphore->mutex)); if(psemaphore->nitems>0) { psemaphore->nitems--; pthread_mutex_unlock(&(psemaphore->mutex)); return 0; } while(psemaphore->nitems <= 0) pthread_cond_wait(&(psemaphore->cond), &(psemaphore->mutex)); psemaphore->nitems--; pthread_mutex_unlock(&(psemaphore->mutex)); return 0; #endif } //信号量 +1 void release_semaphore(wsemaphore *psemaphore) { #ifdef WIN32 ReleaseSemaphore(psemaphore, 1, NULL); #else // sem_post((sem_t *)psemaphore); pthread_mutex_lock(&(psemaphore->mutex)); psemaphore->nitems++; pthread_cond_broadcast(&(psemaphore->cond)); pthread_mutex_unlock(&(psemaphore->mutex)); return; #endif } //销毁信号量 void destroy_semaphore(wsemaphore *psemaphore) { #ifdef WIN32 CloseHandle(psemaphore); #else // sem_destroy((sem_t *)psemaphore); // delete (sem_t *)psemaphore; pthread_cond_destroy(&(psemaphore->cond)); pthread_mutex_destroy(&(psemaphore->mutex)); delete psemaphore; #endif }