接口:
#include <semaphore.h> int sem_timedwait(sem_t *sem, const struct timespec *abs_timeout);
int sem_wait(sem_t *sem); int sem_trywait(sem_t *sem);
Link with -pthread.
//時間樣例
struct timespec { time_t tv_sec; /* 秒 */ long tv_nsec; /* 納秒 */ };
struct timespec ts; ts.tv_nsec = 1000;//納秒 ts.tv_sec += 10;//秒
//等待超時時間未10秒+1000納秒 sem_timedwait(p_sem, &ts);
描述
sem_wait() 遞減(鎖定)由 sem 指向的信號量。如果信號量的值大於零,那么遞減被執行,並且函數立即返回。如果信號量的當前值是零,那么調用將阻塞到它可以執行遞減操作為止(如信號量的值又增長超過零),或者調用被信號打斷。
sem_trywait() 與 sem_wait() 類似,只是如果遞減不能立即執行,調用將返回錯誤(errno 設置為 EAGAIN)而不是阻塞。
sem_timedwait() 與 sem_wait() 類似,只不過 abs_timeout 指定一個阻塞的時間上限,如果調用因不能立即執行遞減而要阻塞。abs_timeout 參數指向一個指定絕對超時時刻的結構,這個結果由自 Epoch,1970-01-01 00:00:00 +0000(UTC) 秒數和納秒數構成。這個結構定義如下:
如果調用時超時時刻已經到點,並且信號量不能立即鎖定,那么 sem_timedwait() 將失敗於超時(errno 設置為ETIMEDOUT)。
如果操作能被立即執行,那么 sem_timedwait() 永遠不會失敗於超時錯誤,而不管 abs_timeout 的值。進一步說,abs_timeout 的驗證在此時沒有進行。
測試程序,在10秒+1000納秒后超時
#include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <semaphore.h> #include <time.h> #include <assert.h> #include <errno.h> #include <signal.h> sem_t sem; #define handle_error(msg) \ do { perror(msg); exit(EXIT_FAILURE); } while (0) static void handler(int sig) { write(STDOUT_FILENO, "sem_post() from handler\n", 24); if (sem_post(&sem) == -1) { write(STDERR_FILENO, "sem_post() failed\n", 18); _exit(EXIT_FAILURE); } } int main(int argc, char *argv[]) { struct sigaction sa; struct timespec ts; int s; if (argc != 3) { fprintf(stderr, "Usage: %s <alarm-secs> <wait-secs>\n", argv[0]); exit(EXIT_FAILURE); } if (sem_init(&sem, 0, 0) == -1) handle_error("sem_init"); /* Establish SIGALRM handler; set alarm timer using argv[1] */ sa.sa_handler = handler; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; if (sigaction(SIGALRM, &sa, NULL) == -1) handle_error("sigaction"); alarm(atoi(argv[1])); /* Calculate relative interval as current time plus number of seconds given argv[2] */ if (clock_gettime(CLOCK_REALTIME, &ts) == -1) handle_error("clock_gettime"); ts.tv_sec += atoi(argv[2]); printf("main() about to call sem_timedwait()\n"); while ((s = sem_timedwait(&sem, &ts)) == -1 && errno == EINTR) continue; /* Restart if interrupted by handler */ /* Check what happened */ if (s == -1) { if (errno == ETIMEDOUT) printf("sem_timedwait() timed out\n"); else perror("sem_timedwait"); } else printf("sem_timedwait() succeeded\n"); exit((s == 0) ? EXIT_SUCCESS : EXIT_FAILURE); }
獲取等待時間+毫秒數
//獲取等待時間+毫秒數 by gettimeofday
//參數: inTimeoutOfUsec 超時時間(單位:微妙)
int getTimeBySystem(struct timespec& inTime, int inTimeoutOfUsec) { struct timeval tv; gettimeofday(&tv, NULL); inTime.tv_sec = tv.tv_sec;//秒數不變 if(inTimeoutOfUsec > 1000 ){ inTimeoutOfUsec = 990; } inTime.tv_nsec = (tv.tv_usec + inTimeoutOfUsec * 1000) * 1000;//毫秒+990延遲 inTime.tv_sec += inTime.tv_nsec / (1000 * 1000 * 1000); inTime.tv_nsec %= 1000 * 1000 * 1000; return 0; }
調用等待API函數
#define SN_SECOND_NSEC 1000000000 #define SN_SECOND_USEC 1000000 /*
in_SemRes:信號量
out_RetCode:返回碼
*/ int waitSemOfCallBack(int InxSolt, sem_t& in_SemRes,int& out_RetCode) { //wait ASRResult callback sem int segVal = 0; sem_getvalue(&(in_SemRes), &segVal); LOG_NOTICE("sem_getvalue():: get current sem value is [%d].",segVal); struct timespec times; int semRetCode = 0; if (clock_gettime(CLOCK_REALTIME, ×) == -1) LOG_NOTICE("clock_gettime failure."); //save current time time_t t_semWaitTime = times.tv_sec; long waitTime = times.tv_nsec; times.tv_sec += 10+20;//添加10s+20s等待時間30s //times.tv_sec += 1;//1s timeout for test while ((semRetCode = sem_timedwait(&in_SemRes, ×)) == -1 && errno == EINTR){ printf("sem_timedwait return EINTR, to continue.\n"); continue; /* Restart if interrupted by handler */ } out_RetCode = 0; /* Check what happened */ if (semRetCode == -1) { if (errno == ETIMEDOUT) { LOG_NOTICE("sem_timedwait() timed out"); out_RetCode = 110; //ETIMEDOUT } else { LOG_NOTICE("sem_timedwait other code[%d].",errno); } } else { LOG_NOTICE("sem_timedwait() succeeded."); out_RetCode = 1;//success } if (clock_gettime(CLOCK_REALTIME, ×) == -1) LOG_NOTICE("clock_gettime failure."); long semWaitTime = (times.tv_sec*SN_SECOND_NSEC + times.tv_nsec) - (t_semWaitTime*SN_SECOND_NSEC + waitTime); //1s= 1000000000ns LOG_INFO("[Idx:%d] wait sem [%d ms] us for result.", InxSolt, semWaitTime/SN_SECOND_USEC); return semRetCode; }
調用trywait
/* outParam: -1(no result), 0(middle result),1(Final result) */ int tryWaitSemOfCallBack(int InxSolt, sem_t& in_SemRes,int& out_RetCode) { int t_iResultType = 0; int segVal = 0; sem_getvalue(&(in_SemRes), &segVal); LOG_NOTICE(" get current sem value is [%d].",segVal); /* invoke sem_trywait */ if ( sem_trywait(&(in_SemRes)) == 0) { rec_t * rec_t_ptr = NULL; pthread_mutex_lock(&mutThread);//加鎖 void *rec_t_ptr = g_mRecArray.front(); g_mRecArray.pop(); pthread_mutex_unlock(&mutThread[m_iSoltInx]);//解鎖 if(rec_t_ptr !=NULL) //判斷隊列不為空 { string result ="[" ; char splitBuf[PHONE_BUFF] = {0}; snprintf(splitBuf,PHONE_BUFF-1,"%s",rec_t_ptr->phone); result=result + "{\"tences\":\""; result = result + splitBuf +"\","; char formatBuf[128] = {0}; memset(formatBuf, 0, 128); snprintf(formatBuf,128-1,"%f",rec_t_ptr->time_stamp); result =result + "\"bTime\":\""+formatBuf+"\","; result = result + "]"; t_iResultType = rec_t_ptr->result_type;//get result type status int t_iResSize = result.size(); printf("get jsonResult size[%d] length %d.\n",result.size(),result.length()); delete rec_t_ptr;//delete buff from queue rec_t_ptr = NULL; } else{ LOG_DEBUG("callback is runing ,get no result from queue.\n"); t_iResultType = -1; } } else{ // Check one of: EAGAIN, EDEADLK, EINTR, EINVAL LOG_INFO("sem_trywait() return code[%d] .",errno); switch(errno){ case EAGAIN: LOG_INFO("sem_trywait() return EAGAIN ."); break; case EDEADLK: LOG_INFO("sem_trywait() return EDEADLK."); break; case EINTR: LOG_INFO("sem_trywait() return EINTR ."); break; case EINVAL: LOG_INFO("sem_trywait() return EINVAL ."); break; default: LOG_INFO("sem_trywait() return other ."); } t_iResultType = -1; } LOG_INFO("index[%d] end."); return t_iResultType; }