易网时代-编程资源站
Welcome
微信登录
编程资源
图片资源库
蚂蚁家优选
PDF转换器
软件资源
软件开发
、
小程序制作
、
系统集成与运维
、
空间租用
、
硬件开发
、
视频监控
、
技术咨询与支持
——联系电话:0311-88999002/88999003
首页
/
操作系统
/
Linux
/
POSIX的pthread_join
join
join是三种同步线程的方式之一。另外两种分别是互斥锁(mutex)和条件变量(condition variable)。
调用pthread_join()将阻塞自己,一直到要等待加入的线程运行结束。
可以用pthread_join()获取线程的返回值。
一个线程对应一个pthread_join()调用,对同一个线程进行多次pthread_join()调用是逻辑错误。
join or detach
线程分两种:一种可以join,另一种不可以。该属性在创建线程的时候指定。
joinable线程可在创建后,用pthread_detach()显式地分离。但分离后不可以再合并。该操作不可逆。
为了确保移植性,在创建线程时,最好显式指定其join或detach属性。似乎不是所有POSIX实现都是用joinable作默认。
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 4
void
*BusyWork(
void
*t)
{
double
result=0.0;
long
tid = (
long
)t;
printf(
"Thread %ld starting... "
,tid);
for
(
int
i=0; i<1000000; i++)
{
result = result + sin(i) * tan(i);
}
printf(
"Thread %ld done. Result = %e "
,tid, result);
pthread_exit((
void
*) t);
}
int
main (
int
argc,
char
*argv[])
{
pthread_t
thread
[NUM_THREADS];
pthread_attr_t attr;
// 1/4: init
pthread_attr_init(&attr);
// 2/4: explicitly specify as joinable or detached
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
int
rc;
long
t;
for
(t=0; t<NUM_THREADS; t++)
{
printf(
"Main: creating thread %ld "
, t);
// 3/4: use thread attribute
rc = pthread_create(&
thread
[t], &attr, BusyWork, (
void
*)t);
if
(rc) {
printf(
"ERROR; return code from pthread_create() is %d "
, rc);
exit(-1);
}
}
// 4/4: release thread attribute
pthread_attr_destroy(&attr);
void
*status;
for
(t=0; t<NUM_THREADS; t++)
{
rc = pthread_join(
thread
[t], &status);
if
(rc) {
printf(
"ERROR; return code from pthread_join() is %d "
, rc);
exit(-1);
}
printf(
"Main: completed join with thread %ld having a status of %ld "
,t,(
long
)status);
}
printf(
"Main: program completed. Exiting. "
);
return
0;
}
收藏该网址
版权所有©石家庄振强科技有限公司2024
冀ICP备08103738号-5
网站地图