关于Linux 线程pthread_join的用法
发布网友
发布时间:2022-04-19 22:23
我来回答
共2个回答
热心网友
时间:2023-01-21 22:55
Linux系统pthread_join用于挂起当前线程(调用pthread_join的线程),直到thread指定的线程终止运行为止,当前线程才继续执行。
案例代码:
/*******************************************
** Name:pthread_join.c
** 用于Linux下多线程学习
** 案例解释线程的暂停和结束
** Author:admin
** Date:2015/8/11
** Copyright (c) 2015,All Rights Reserved!
**********************************************
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
void *thread(void *str)
{
int i;
//不调用pthread_join线程函数
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线程函数
pthread_join(pth, NULL);
for (i = 0; i < 10; ++i)
{
sleep(1);
printf( "This in the main : %d\n" , i );
}
return 0;
}
通过Linux下shell命令执行上面的案例代码:
[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
这说明pthread_join函数的调用者在等待子线程退出后才继续执行。
热心网友
时间:2023-01-22 00:13
这是随机情况,由系统调度决定,不是唯一的结果,你可以尝试这样改:ret=pthread_create(&threadids[i], NULL, myThread, (void*)i);
sleep(1);
这样就是按顺序创建线程