【发布时间】:2014-07-15 18:02:13
【问题描述】:
我有一个捕获程序,它除了捕获数据并将其写入文件还打印一些统计数据。打印统计数据的函数
static void report(void)
{
/*Print statistics*/
}
使用每秒到期的 ALARM 大约每秒调用一次。所以程序就像
void capture_program()
{
pthread_t report_thread
while()
{
if(pthread_create(&report_thread,NULL,report,NULL)){
fprintf(stderr,"Error creating reporting thread! \n");
}
/*
Capturing code
--------------
--------------
*/
if(doreport)
/*wakeup the sleeping thread.*/
}
}
void *report(void *param)
{
//access some register from hardware
//sleep for a second
}
计时器到期设置doreport 标志。如果设置了此标志,则调用report() 清除该标志。
当定时器在主线程中关闭时,我如何唤醒睡眠线程(运行 report())?
【问题讨论】:
-
您正在寻找的是某种event-signaling mechanism。将其与您的标志结合使用(并在链接文档中查找虚假唤醒以了解原因)。
-
考虑扔掉你所拥有的,然后只使用
timer_create系列调用而不是alarm。它们允许您指定一个特定线程(或每次创建一个新线程)来将信号定向到。这正是你想要做的。否则,您必须阻止特定线程中的信号以强制它们被传递到您想要的那个,或者,或者,进入一些 condvars 之类的兔子洞。现在咬紧牙关,做正确的事。
标签: c multithreading pthreads posix