linux学习笔记8 线程

本文详细介绍了在Linux环境下如何使用pthread库创建和回收线程,包括pthread_create和pthread_join函数的使用方法,并通过示例代码展示了如何创建线程并等待其完成。

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

1.创建线程

函数原型:int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);

参数描述:thread是线程id,是传出参数,只需要提供一个地址即可

attr是线程属性,一般为NULL

start_routine是线程执行的函数,函数定义为void *func (void *)。

arg是线程执行函数的参数

程序举例:创建一个进程

#include <iostream>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>


using namespace std;
void *thr(void * agr)//void *定义的是无类型指针,可以将任意一种类型的指针赋给无类型指针
{
	sleep(1);
	cout<<"i am a thread, pid = "<<getpid()<<" thread = "<<pthread_self()<<endl;
        return NULL;//线程中可以使用return,但是主控线程不能使用return,这样就会把进程给结束了
}

int main()
{
	pthread_t tid;
	pthread_create(&tid, NULL, thr, NULL);
	cout<<"i am a main thread, pid ="<<getpid()<<" thread = "<<pthread_self()<<endl;
	sleep(2);//如果这句程序没有,整个进程就会结束了,那么建立的线程根本没有机会执行。
//这里可以把sleep函数换成pthread_create(NULL),效果一样。
}

2.回收线程

函数原型:int pthread_join(pthread_t thread, void **retval);

函数描述:thread是要回收的线程号, retval是线程执行函数的返回值。

程序举例:

#include <iostream>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>


using namespace std;
void *thr(void * agr)
{
	sleep(1);
	cout<<"i am a thread, pid = "<<getpid()<<"thread = "<<pthread_self()<<endl;
	return (void*)100;
}

int main()
{
	pthread_t tid;
	pthread_create(&tid, NULL, thr, NULL);
	cout<<"i am a main thread, pid ="<<getpid()<<"thread = "<<pthread_self()<<endl;
	void *ret;
	pthread_join(tid, &ret);//这里的ret就是100。
	sleep(2);
}

函数原型:int pthread_detach(pthread_t tid);

函数描述:tid是要回收的线程号

这两个函数一般join是由主线程来调用,而detach则由子线程自己调用,在调用join之后,主线程会一直阻塞等待子线程执行任务结束,然后回收子线程,而调用detach之后,等待子线程执行任务结束之后,会自动回收子线程的资源。

至于具体原理可以看这篇博客:

https://blog.youkuaiyun.com/weibo1230123/article/details/81410241

注意:pthread_join一般是主线程调用,而pthread_detach是本线程自己调用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值