liv*_*hak 2 c multithreading posix pthreads
我有一个捕获程序,它除了捕获数据并将其写入文件还打印一些统计信息。打印统计信息的函数
static void* report(void)
{
/*Print statistics*/
}
Run Code Online (Sandbox Code Playgroud)
使用每秒到期的 ALARM 大约每秒调用一次。所以程序就像
void capture_program()
{
pthread_t report_thread;
while (!exit_now )
{
if (pthread_create(&report_thread,NULL,report,NULL)) {
fprintf(stderr,"Error creating reporting thread! \n");
}
/*
Capturing code
--------------
--------------
*/
if(doreport)
usleep(5);
}
}
void *report(void *param)
{
while (true)
{
if (doreport)
{
doreport = 0
//access some register from hardware
usleep(5)
}
}
}
Run Code Online (Sandbox Code Playgroud)
计时器到期设置doreport标志。如果设置了这个标志report(),它会清除标志。我正在使用 usleep 在程序中的两个线程之间交替。这似乎工作正常。我还有一个信号处理程序来处理 SIGINT(即 CTRL+C)
static void
anysig(int sig)
{
if (sig != SIGINT)
dagutil_set_signal_handler(SIG_DFL);
/* Tell the main loop to exit */
exit_now = 1;
return;
}
Run Code Online (Sandbox Code Playgroud)
我的问题:
1) Is it safe to call pthread_join from inside the signal handler?
2) Should I use exit_now flag for the report thread as well?
Run Code Online (Sandbox Code Playgroud)
真的,不要那样做。
我找不到任何暗示pthread_join异步信号安全的参考(默认情况下,您应该假设它们不是)。
但即使是这样,你建议的做法也非常丑陋。
在您的信号处理程序中,只需在sig_atomic_t变量中设置一个标志来表示信号已发生。然后定期轮询,并在信号处理程序之外写入统计信息或加入线程。
如果您不喜欢轮询,另一种巧妙的技术是“自写管道”。在信号处理程序写入写入端的位置设置一个管道(write异步安全)并在主select()循环或其他任何地方读取。
| 归档时间: |
|
| 查看次数: |
1482 次 |
| 最近记录: |