【问题标题】:How to correctly use sem_timedwait()如何正确使用 sem_timedwait()
【发布时间】:2016-08-28 21:27:51
【问题描述】:
如果我的程序中的线程在 10 秒后不能减少信号量(另一个线程可以或不能增加它),我正试图让我的程序停止
我看到我可以为此使用 sem_timedwait() 但我在网上找不到一个很好的例子。
所以我只想替换这个:
sem_wait(&full);
//go on with stuff
类似这样的:
sem_timedwait(&full,someTimeStuffThatRepresents10Secs);
if(sem_timedwaitTookLongerThan10){
pthread.exit(NULL);
}else{
//do stuff
}
感谢任何帮助!
【问题讨论】:
标签:
c
time
pthreads
semaphore
【解决方案1】:
/* Calculate relative interval as current time plus 10 seconds */
struct timespec ts;
if (clock_gettime(CLOCK_REALTIME, &ts) == -1)
{
/* handle error */
return -1;
}
ts.tv_sec += 10;
while ((s = sem_timedwait(&full, &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");
Linux 程序员手册在
上给出了详细的示例
SEM_WAIT(3)
请在控制台输入man sem_timedwait 或访问文档online。