pthread_kill
pthread_kill函数是用来向线程发送signal。类似于我们在linux下使用kill命令向指定的进程发送signal。
函数原型:
NAME
pthread_kill - send a signal to a thread
SYNOPSIS
#include <signal.h>
int pthread_kill(pthread_t thread, int sig);
DESCRIPTION
The pthread_kill() function sends the signal sig to thread, a thread in the same process as the caller. The signal is asyn‐
chronously directed to thread.
If sig is 0, then no signal is sent, but error checking is still performed.
以上是从man手册上获取的pthread_kill函数的信息,可以看出pthread_kill其实就是用来向指定的线程发送sig信号,然后执行对应的信号处理函数。
但是最后写了一个sig is 0的情况,在int sig参数为0的时候,可以用来判定线程的存活情况。
RETURN VALUE 为0,表示线程存在。
RETURN VALUE 为ESRCH,表示线程不存在。
RETURN VALUE为 EINVAL,表示信号不合法。
所以pthread_kill(thread_id,0)就可以用来检测线程的情况,来进行不同的处理。
int ret = pthread_kill(thread_id,0);
if (ret == ESRCH) {
printf("the specified thread did not exists or already quit\n");
} else if (ret == EINVAL)
printf("signal is invalid\n");
else {
printf("the thread is alive\n");
}