Linux学习笔记:Linux线程基本操作

本文详细介绍了线程操作的基础知识,包括线程的创建、获取线程ID、线程退出、线程取消、线程等待、线程分离以及线程清理函数的使用方法。通过具体的函数调用示例,帮助读者理解线程管理的核心概念。

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

头文件:#include <pthread.h>

编译:Compile and link with -pthread.

编译指令: gcc thread.c -o thread -lpthread

1、创建线程

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                              void *(*start_routine) (void *), void *arg);
2、获取线程id

pthread_t pthread_self(void);

3、线程退出

void pthread_exit(void *retval);
终止自身。

4、线程取消

int pthread_cancel(pthread_t thread);
可从其他线程终止。

5、线程等待

int pthread_join(pthread_t thread, void **retval);
阻塞时等待,可用于在线程结束后手动释放资源。

6、线程分离

int pthread_detach(pthread_t thread);
线程分离后,其资源可在线程结束后自动释放。

7、线程清理函数

void pthread_cleanup_push(void (*routine)(void *),
                                 void *arg);
 void pthread_cleanup_pop(int execute);

execute参数表示执行到pthread_cleanup_pop()时是否在弹出清理函数的同时执行该函数,为0表示不执行,非0为执行;这个参数并不影响异常终止时清理函数的执行。
参考资料:http://www.xinyingda.cn/bbs/wapbencandy.php?fid=15&id=1081

参考资料:https://blog.csdn.net/qq_42169059/article/details/89380498

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值