我有一个关于pthread_kill()行为的问题。关于pthread_kill()行为
这里有一个小的代码我尝试:
void my_handler1(int sig)
{
printf("my_handle1: Got signal %d, tid: %lu\n",sig,pthread_self());
//exit(0);
}
void *thread_func1(void *arg)
{
struct sigaction my_action;
my_action.sa_handler = my_handler1;
my_action.sa_flags = SA_RESTART;
sigaction(SIGUSR1, &my_action, NULL);
printf("thread_func1 exit\n");
}
void *thread_func2(void *arg)
{
int s;
s = pthread_kill(tid1_g,SIGUSR1);
if(s)
handle_error(s,"tfunc2: pthread_kill");
printf("thread_func2 exit\n");
}
int main()
{
int s = 0;
pthread_t tid1;
s = pthread_create(&tid1,NULL,thread_func1,NULL);
if(s)
handle_error(s,"pthread_create1");
tid1_g = tid1;
printf("tid1: %lu\n",tid1);
s = pthread_join(tid1,NULL);
if(s)
handle_error(s, "pthread_join");
printf("After join tid1\n");
pthread_t tid3;
s = pthread_create(&tid3,NULL,thread_func2,NULL);
if(s)
handle_error(s,"pthread_create3");
s = pthread_join(tid3,NULL);
if(s)
handle_error(s, "pthread_join3");
printf("After join tid3\n");
return 0;
}
我得到的输出是:
tid1: 140269627565824
thread_func1 exit
After join tid1
my_handle1: Got signal 10, tid: 140269627565824
thread_func2 exit
After join tid3
所以,即使我一个线程调用pthread_kill()已经完成,该线程的处理程序仍然被调用。在线程不存在的情况下,pthread_kill()是否应该返回错误(ESRCH)?
只有当线程连接或分离时退出。如果线程已经死了,但仍然可以连接,那么它是非常明确的。 – 2012-02-28 19:07:24
谢谢!更新了我的回答:) – 2012-02-28 19:09:35
编辑不正确; POSIX说没有这样的事情。前一版本的POSIX(2001)错误地给出了这样的印象:如果“实现检测到”线程不再存在,则说几个函数“应该失败”。请注意,没有要求实施必须检测到这种情况;只有它,它确实需要使用特定的错误代码。许多执行者和应用程序作者错误地将此视为执行通常不可能做到的事情。 POSIX 2008已经解决了所有这些问题。 – 2012-02-28 19:15:29