在未发出条件变量的情况下设置settimer()和SIGALRM

时间:2019-05-05 22:18:33

标签: c multithreading time signals condition-variable

我对settimer()和SIGALRM及其工作方式存在一些实际问题。

假设我创建了一些线程:(已编辑)

#define _POSIX_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
#include <time.h>
#include <sys/time.h> 
#include <signal.h> 

pthread_mutex_t lock;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;

void timer_handler (int signum)
{
  printf ("\n[WAITING LINE] All our assistants are busy at the moment,we apologize. Please wait on the line\n");
}

void* threadFunc(void* arg){

        struct itimerval timer;
        if (signal(SIGALRM, (void (*)(int)) timer_handler) == SIG_ERR) {
            perror("Unable to catch SIGALRM");
            exit(1);
        }
        timer.it_value.tv_sec =1;
        timer.it_value.tv_usec = 0;


    while(mycond){
        if(setitimer (ITIMER_REAL, &timer, NULL)){
            perror("error calling setitimer()");
            exit(1);
        }

        pthread_cond_wait(&cond1,&lock);

        //doing other things that take significant time
    }


}

int main(){

//initializing mutex
....

//creating the threads
....
//waiting the threads to join
....
return 0;

}

我没有得到应该每20毫秒显示一次的消息。 在示例中,我遵循了setTimer之后实现了while(1)的情况,但
我无法执行此操作,因为我希望在线程等待条件信号时显示此消息。 其余代码中实现的内容并不重要,我们假设完成并发出条件信号要花费比20ms多得多的时间。

我应该怎么做才能每20ms接收一次timer_handler消息,而尚未发出状态信号呢?

我对同时使用条件变量和settimer()还是陌生的,因此希望能对理解它们和解决任何误解有所帮助。

1 个答案:

答案 0 :(得分:0)

如果所有线程都被阻止,则虚拟计时器的时钟将不会运行。 您可能需要切换到ITIMER_REAL。 (还请注意,您不应在信号处理程序中使用异步信号不安全的功能,例如printf。)