关于pthread_kill()行为

Cha*_*ngi 3 c operating-system pthreads

我有一个关于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;
}
Run Code Online (Sandbox Code Playgroud)

我得到的输出是:

tid1: 140269627565824
thread_func1 exit
After join tid1
my_handle1: Got signal 10, tid: 140269627565824
thread_func2 exit
After join tid3
Run Code Online (Sandbox Code Playgroud)

所以,即使我在已经完成的线程上调用pthread_kill(),该线程的处理程序仍然被调用.如果线程不存在,是不是pthread_kill()应该返回错误(ESRCH)?

R..*_*R.. 7

pthread_t线程在其生命周期之后的任何使用(*)(即在pthread_join成功返回之后,或者在线程终止于分离状态之后)导致未定义的行为.您应该只想到ESRCH如果pthread_t仍然有效,也就是说,如果你还没有加入线程呢.否则所有投注都会被取消.

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