linux进阶43——多线程程序设计(三):线程等待

本文详细介绍了pthread_join函数在多线程编程中的作用,它用于阻塞主线程直到指定线程结束。通过示例代码展示了如何使用pthread_join获取线程的返回值,并解释了可能的错误码及其含义。了解这一函数对于进行有效的线程同步至关重要。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

线程等待

函数定义

#include <pthread.h>

int pthread_join(pthread_t tid, void **rval_ptr);

阻塞调用线程,直到指定的线程终止。

返回值

成功返回0,失败返回错误码。

错误码定义如下:

ERRORS
       EDEADLK
              A deadlock was detected (e.g., two threads tried to join with each other); or thread specifies the calling thread.(检测到死锁)

       EINVAL thread is not a joinable thread.(不是可连接的线程)

       EINVAL Another thread is already waiting to join with this thread.(另一个线程已经在等待加入这个线程)

       ESRCH  No thread with the ID thread could be found.(找不到对应ID的线程)

参数

tid:等待退出的线程id

rval_ptr:线程退出的返回值指针

示例

#include <pthread.h>
#include <unistd.h>
#include <stdio.h>

void *myThread(void *str)
{
	for(int i = 0; i < 5; i++)
	{
		sleep(2);
		printf("child thread is : %d\n", i);
	}

	return NULL;
}

int main()
{
	pthread_t tid;
	int ret, i;

	ret = pthread_create(&tid, NULL, myThread, NULL);
	if(ret != 0)
	{
		printf("thread create error!\n");
		return -1;
	}

	ret = pthread_join(tid, NULL);
	if(ret != 0)
	{
		printf("thread join error!\n");
		return -2;
	}

	for(i = 0; i < 5; i++)
	{
		sleep(1);
		printf("main thread is : %d\n", i);
	}

	return 0;
}

编译运行:

[root@192 pthread]# gcc -lpthread pthread_join.c -o pthread_join
[root@192 pthread]# ./pthread_join
child thread is : 0
child thread is : 1
child thread is : 2
child thread is : 3
child thread is : 4
main thread is : 0
main thread is : 1
main thread is : 2
main thread is : 3
main thread is : 4
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值