NAME
pthread_join - wait for thread termination 等待直到线程终止
SYNOPSIS
#include <pthread.h>
int pthread_join(pthread_t thread, void **value_ptr);
DESCRIPTION
The pthread_join() function suspends execution of the calling thread until the target thread terminates, unless the target thread has already terminated. On return from a successful pthread_join() call with a non-NULL value_ptr argument, the value passed to pthread_exit() by the terminating thread is made available in the location referenced by value_ptr. When a pthread_join() returns successfully, the target thread has been terminated. The results of multiple simultaneous calls to pthread_join() specifying the same target thread are undefined. If the thread calling pthread_join() is canceled, then the target thread will not be detached.
It is unspecified whether a thread that has exited but remains unjoined counts against _POSIX_THREAD_THREADS_MAX.
RETURN VALUE
If successful, the pthread_join() function returns zero. Otherwise, an error number is returned to indicate the error.
ERRORS
The pthread_join() function will fail if:
[EINVAL]
The implementation has detected that the value specified by thread does not refer to a joinable thread.
[ESRCH]
No thread could be found corresponding to that specified by the given thread ID.
The pthread_join() function may fail if:
[EDEADLK]
A deadlock was detected or the value of thread specifies the calling thread.
The pthread_join() function will not return an error code of [EINTR].
EXAMPLES
None.
APPLICATION USAGE
None.
FUTURE DIRECTIONS
None.
int pthread_join(pthread_t thread, void **value_ptr);
thread:等待退出线程的线程号。
value_ptr:退出线程的返回值。
范例:
//pthread_join.c
// 子线程阻塞,等待信号,然后输出字符串
// 主线程从键盘录入字符,给子线程发信号。
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <pthread.h>
#include <time.h>
pthread_t tid;
sigset_t set;
void myfunc()
{
printf("hello\n");
}
static void* mythread(void *p)
{
int signum;
while(1){
sigwait(&set,&signum);
if(SIGUSR1 == signum)
myfunc();
if(SIGUSR2 == signum)
{
printf("I will sleep 2 second and exit\n");
sleep(2);
break;
}
}
}
int main()
{
char tmp;
void* status;
sigemptyset(&set);
sigaddset(&set,SIGUSR1);
sigaddset(&set,SIGUSR2);
sigprocmask(SIG_SETMASK,&set,NULL);
pthread_create(&tid,NULL,mythread,NULL);
while(1)
{
printf(":");
scanf("%c",&tmp);
if('a' == tmp)
{
pthread_kill(tid,SIGUSR1); //发送SIGUSR1,打印字符串。
}
else if('q'==tmp)
{
pthread_kill(tid,SIGUSR2); //发出SIGUSR2信号,让线程退出,如果发送SIGKILL,线程将直接退出。
pthread_join(tid,&status); //等待线程tid执行完毕,这里阻塞。
printf("finish\n");
break;
}
else
continue;
}
return 0;
}
编译 gcc -o pthread_join -lpthread pthread_join.c
运行结果:
// 如果输入a,子线程打印"hello",主程序继续等待输入;
// 如果输入q,主程序等待子程序结束。子线程打印"I will sleep 2 second and exit",并延时两秒后结束。主线程随之打印"finish",程序结束。