接口:
#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 ", 24); if (sem_post(&sem) == -1) { write(STDERR_FILENO, "sem_post() failed ", 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> ", 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() "); 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 "); else perror("sem_timedwait"); } else printf("sem_timedwait() succeeded "); 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. "); 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. ",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. "); 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; }