C语言 pthread_join

线程回收
pthread_join,阻塞等待线程退出,获取线程退出状态,对应进程中 waitpid() 函数
int pthread_join(pthread_t thread, void **retval);
返回
成功:0;失败:错误号
参数:
thread:线程ID (不是指针);
retval:所调用函数的返回值

对比进程

进程中:main返回值、exit参数–>int;等待子进程结束 wait 函数参数–>int *
线程中:线程主函数返回值、pthread_exit–>void *;等待线程结束 pthread_join 函数参数–>void **

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

void *tfn(void *arg)//线程函数
{
	printf("线程 Thread_ID = %lu\n", pthread_self());
	sleep(5);
	return NULL;
}

int main(void)
{
	pthread_t tid;
	pthread_create(&tid, NULL, tfn, NULL);//创建线程
	void *ret;
	pthread_join(tid,&ret);//线程回收
	printf("ret return %d\n", (int)ret);

	return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
pthread_create函数是C语言中用于创建一个新的线程的函数。它的原型如下: ```c #include <pthread.h> int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg); ``` 这个函数会创建一个新的线程,并将新线程的标识符存储在thread指针指向的内存位置。新线程的执行将从start_routine函数开始,start_routine函数的参数是一个指向void的指针,可以传递任意类型的数据给新线程。 在创建线程时,还可以通过attr参数传递线程属性,例如设置线程的栈大小、调度策略等。如果不需要设定特定的属性,可以将attr参数设为NULL。 创建线程成功时,pthread_create函数返回0,否则返回一个非零的错误码,表示创建线程失败。 下面是一个简单的例子,演示如何使用pthread_create函数创建一个新线程: ```c #include <stdio.h> #include <pthread.h> void *thread_func(void *arg) { printf("Hello from the new thread!\n"); pthread_exit(NULL); } int main() { pthread_t thread; // 创建新线程 int ret = pthread_create(&thread, NULL, thread_func, NULL); if (ret != 0) { printf("Failed to create thread.\n"); return 1; } // 等待新线程结束 pthread_join(thread, NULL); printf("Back to the main thread.\n"); return 0; } ``` 这个例子中,主线程调用pthread_create函数创建一个新线程,并传递给它一个名为thread_func的函数作为新线程的入口。新线程会打印一条消息,然后调用pthread_exit函数退出。主线程使用pthread_join函数等待新线程结束后再继续执行。 注意:在使用pthread_create函数时,需要链接pthread库,可以在编译时加上-lpthread选项。例如: ``` gcc -o program program.c -lpthread ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值