关于pthread_kill()行为 [英] About pthread_kill() behavior

查看:124
本文介绍了关于pthread_kill()行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对pthread_kill()行为有疑问.

I have a question about pthread_kill() behavior.

这是我正在尝试的一小段代码:

Here's a small code I'm trying out:

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)?

So, even though I'm calling pthread_kill() on a thread that has already finished, the handler for that thread is still getting called. Isn't pthread_kill() supposed to return error(ESRCH) in case the thread doesn't exist?

推荐答案

在线程的生存期(即pthread_join成功返回之后)对线程使用pthread_t的任何(*)线程终止为分离状态后)会导致未定义的行为.如果pthread_t仍然有效,即您尚未加入该线程,则应该只期望ESRCH.否则,所有投注都将取消.

Any use (*) of the pthread_t for a thread after its lifetime (i.e. after pthread_join successfully returns, or after the thread terminates in the detached state) results in undefined behavior. You should only expect ESRCH if the pthread_t is still valid, i.e. if you haven't joined the thread yet. Otherwise all bets are off.

注意:通过使用"(*),我的意思是将其传递给标准库中的pthread_函数.据我所知,仅将其分配给另一个pthread_t变量或以其他方式在您自己的函数之间传递而不使用它"就不会导致UB.

Note: By "use" (*), I mean passing it to a pthread_ function in the standard library. As far as I can tell, merely assigning it to another pthread_t variable or otherwise passing it around between your own functions without "using" it doesn't result in UB.

这篇关于关于pthread_kill()行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆