pthread_cond_wait() 和信号,结果取决于操作系统 [英] pthread_cond_wait() and signal, the result depend on OS
问题描述
我是多线程编程的初学者,现在我知道在使用 pthead_cond_wait()
等待时发送信号时,结果取决于操作系统.有人能告诉我如何知道呼叫是如何被中断的,以及如何编写可移植的代码吗?
I am a beginner of multi-threaded programming, and now I know that when a signal was sent while waiting with pthead_cond_wait()
, the result depends on the OS.
Can somebody tell me how to know how the call was interrupted, and how to write portable code?
#include <stdio.h>
#include <signal.h>
#include <pthread.h>
void
sigusr1_handler(int sig)
{
printf("signal called\n");
}
int
main()
{
int n;
pthread_mutex_t mut;
pthread_cond_t cond;
struct timespec ts;
signal(SIGUSR1, sigusr1_handler);
pthread_mutex_init(&mut, NULL);
pthread_cond_init(&cond, NULL);
pthread_mutex_lock(&mut);
printf("before cond_wait\n");
n = pthread_cond_wait(&cond, &mut);
printf("after pthread_cond_wait : %d\n", n);
perror("error pthread_cond_wait:");
pthread_mutex_unlock(&mut);
return 0;
}
<小时>
MacOS X 10.11.4
cc -o condwait condwait.c -lpthread
Linux 2.6.32-642.3.1.el6.x86_64
gcc -o condwait condwait.c -lpthread
Solaris11 5.11 11.2
cc -D_POSIX_C_SOURCE -D_REENTRANT -mt -o condwait condwait.c -lpthread
MacOS X
$ ./condwait &
[1] xxxxx
$ kill -USR1 %1
signal called
after pthread_cond_wait : 0
error pthread_cond_wait:: Unknown error: 260
Solaris
$ ./condwait &
[1] xxxxx
$ kill -USR1 %1
signal called
after pthread_cond_wait : 0
error pthread_cond_wait : Error 0
Linux
$ ./condwait &
[1] xxxxx
$ kill -USR1 %1
signal called
$ jobs
[1]+ Running
当使用 Solaris 原生 cond_wait()
时,它会按照文档返回 EINTR
.有没有办法知道 pthread_cond_wait()
被中断了?
When using Solaris native cond_wait()
, it returns EINTR
as documented.
Is there any idea how to know that pthread_cond_wait()
was interrupted?
推荐答案
POSIX 指定此函数永远不会返回 EINTR.对于遗留操作系统的可移植性,您无论如何都可以检查它,它不会受到伤害
POSIX specifies that this function will never return EINTR. For portability to legacy OSes you can check for it anyway, it doesn't hurt
更重要的是,您应该为虚假唤醒做好准备.该函数可以在任何时间以任何原因返回零,但条件不满足.互斥将被锁定.您必须检查条件,如果不满足,则返回 pthread_cond_wait.
More importantly, you should be prepared for spurious wakeups. The function can return zero at any time for any reason wiith the condition not being met. The mutex will be locked. You have to check the condition and, if not met, go back to pthread_cond_wait.
这篇关于pthread_cond_wait() 和信号,结果取决于操作系统的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!