IPC:每秒从客户端收集数据

时间:2019-11-26 19:36:51

标签: c pthreads semaphore

我想从连接到服务器的所有客户端收集数据,并且我最多要等待1秒钟。如何使用信号量? 我当前的代码:

int players=2;
while(1){
    //request for choice
    for(int i = 0; i<players; i++)
        sem_post(&sharedMemory->request_choice);
    //wait for data
    for (int i = 0;i<players; i++)
        //ok..I have data but not in 1 second..
        sem_wait(&sharedMemory->got_choice);


    //updating data..
}

1 个答案:

答案 0 :(得分:1)

POSIX platforms provide sem_timedwait()

  

简介

#include <semaphore.h>
#include <time.h>

int sem_timedwait(sem_t *restrict sem,
       const struct timespec *restrict abstime);
     

描述

     

sem_timedwait()函数应锁定由引用的信号量   semsem_wait()函数一样。但是,如果信号量   无法等待其他进程或线程才能锁定   通过执行sem_post()函数来解锁信号量,这个等待   在指定的超时时间到期时应终止。

     

当绝对时间指定为绝对时间时,超时将终止   通过,以超时所依据的时钟为准(即,   该时钟的值等于或超过abstime时),或者   abstime指定的绝对时间已在   通话时间。

     

超时应基于CLOCK_REALTIME时钟。的   超时的分辨率应为时钟的分辨率   它基于的。 timespec数据类型定义为结构   在<time.h>标头中。

     

在任何情况下,如果   信号量可以立即锁定。 abstime的有效性   无需检查信号量是否可以立即锁定。

     

返回值

     

如果调用sem_timedwait()函数应返回零   进程成功执行了对   由sem指定的信号量。如果呼叫失败,则状态为   信号量的值应保持不变,并且该函数应返回一个   值-1并设置errno来指示错误。

     

错误

     

在以下情况下,sem_timedwait()函数将失败:

     

...

[ETIMEDOUT]
    The semaphore could not be locked before the specified timeout expired.

该链接还提供了此示例用法:

/* Calculate relative interval as current time plus
   number of seconds given argv[2] */


if (clock_gettime(CLOCK_REALTIME, &ts) == -1) {
    perror("clock_gettime");
    exit(EXIT_FAILURE);
}
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 */