SYNOPSIS
#include
int pthread_join(pthread_t thread, void **rval_ptr);
DESCRIPTION
The pthread_join() function shall suspend execution of the calling thread until the target thread terminates, unless the target thread has already termi-nated. 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 shall be made available in the location referenced by rval_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 shall not be detached.
pthread_join用于挂起当前线程(调用pthread_join的线程),直到thread指定的线程终止运行为止,当前线程才继续执行。thread指定的线程的返回值由rval_ptr返回。一个线程所使用的资源在对该线程调用pthread_join之前不会被重新分配,因此对于每个切入的线程必须调用一次pthread_join函数。线程必须可切入的而不是处于被分离状态,并且其他线程不能对同一线程再次应用pthread_join调用。通过pthread_create调用中使用一个适当的attr参数或者调用pthread_detach可以让一个线程处于被分离状态。
/********************************************************************************************
** Name:pthread_join.c
** Used to study the multithread programming in Linux OS
** A example showing a thread to be waited to end.
** Author:zeickey
** Date:2008/6/28
** Copyright (c) 2006,All Rights Reserved!
*********************************************************************************************/
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
void *thread(void *str)
{
int i;
for (i = 0; i < 10; ++i)
{
sleep(2);
printf( "This in the thread : %d\n" , i );
}
return NULL;
}
int main()
{
pthread_t pth;
int i;
int ret = pthread_create(&pth, NULL, thread, (void *)(i));
pthread_join(pth, NULL);
for (i = 0; i < 10; ++i)
{
sleep(1);
printf( "This in the main : %d\n" , i );
}
return 0;
}
|
"pthread_join(pth, NULL);"这一行注释掉:
[root@localhost src]# gcc pthread_join.c -lpthread
[root@localhost src]# ./a.out
This in the main : 0
This in the thread : 0
This in the main : 1
This in the main : 2
This in the thread : 1
This in the main : 3
This in the main : 4
This in the thread : 2
This in the main : 5
This in the main : 6
This in the thread : 3
This in the main : 7
This in the main : 8
This in the thread : 4
This in the main : 9
子线程还没有执行完毕,main函数已经退出,那么子线程也就退出了。
“pthread_join(pth, NULL);”起作用
[root@localhost src]# gcc pthread_join.c -lpthread
[root@localhost src]# ./a.out
This in the thread : 0
This in the thread : 1
This in the thread : 2
This in the thread : 3
This in the thread : 4
This in the thread : 5
This in the thread : 6
This in the thread : 7
This in the thread : 8
This in the thread : 9
This in the main : 0
This in the main : 1
This in the main : 2
This in the main : 3
This in the main : 4
This in the main : 5
This in the main : 6
This in the main : 7
This in the main : 8
This in the main : 9
[root@localhost src]#
这说明pthread_join函数的调用者在等待子线程退出后才继续执行
|
阅读(4385) | 评论(0) | 转发(2) |