[9]Linux多线程

相关函数API支持:

phread支持库:

Linux系统下的多线程遵循POSIX线程接口,称为pthread。编写Linux下的多线程程序,需要使用头文件pthread.h,连接时需要使用库libpthread.a。

gcc -lpthread helloworld.c -o helloworld

创建线程:

#include <pthread.h>
int pthread_create(pthread_t * tidp,const pthread_attr_t *attr,void *(*start_rtn)(void),void *arg);
  • tidp:线程id(输出参数);
  • attr:线程属性(通常为空);
  • start_rtn:线程要执行的函数;
  • arg:start_rtn的参数;
  • 返回值:成功,返回0;出错,返回-1。

线程终止:

如果进程中任何一个线程中调用exit或_exit,那么整个进程都会终止。线程的正常退出方式有:
(1) 线程从启动例程中返回;
(2) 线程可以被进程中的另一个线程程终止;
(3) 线程自己调用pthread_exit函数。

pthread_exit

#include <pthread.h>
void pthread_exit(void * rval_ptr);

使用函数pthread_exit退出线程,这是线程的主动行为;由于一个进程中的多个线程是共享数据段的,因此通常在线程退出之后,退出线程所占用的资源并不会随着线程的终止而得到释放。pthread_exit()调用线程的返回值,可由其他函数如pthread_join来检索获取。
rval_ptr:线程返回值指针。

pthread_join

#include <pthread.h>
int pthread_join(pthread_t tid,void **rval_ptr);

阻塞调用线程,直到指定的线程终止。
tid :等待退出的线程id;
rval_ptr:线程退出的返回值的指针;
返回值:成功返回0,否则返回非0。

线程标识

#include <pthread.h>
pthread_t pthread_self(void)

获取调用线程的线程标识。

线程终止与资源释放

线程终止

线程终止有两种情况:正常终止和非正常终止。线程主动调用pthread_exit或者从线程函数中return都将使线程正常退出,这是可预见的退出方式;非正常终止是线程在其他线程的干预下,或者由于自身运行
出错(比如访问非法地址)而退出,这种退出方式是不可预见的。
不论是可预见的线程终止还是异常终止,都会存在资源释放的问题,如何保证线程终止时能顺利的释放掉自己所占用的资源,是一个必须考虑解决的问题。

资源释放

在POSIX线程API中提供了一个pthread_cleanup_push()/pthread_cleanup_pop()函数对用于自动释放资源 –从pthread_cleanup_push()的调用点到pthread_cleanup_pop()之间的程序段中的终止动作(包括调用 pthread_exit()和取消点终止)都将执行pthread_cleanup_push()所指定的清理函数。

#include <pthread.h>
void pthread_cleanup_push(void (*rtn)(void *),void *arg);

将清除函数压入清除栈。
- rtn:清除函数(函数指针)
- arg:清除函数的参数

#include <pthread.h>
void pthread_cleanup_pop(int execute);

将清除函数弹出清除栈。
- execute执行到pthread_cleanup_pop()时是否在弹出清理函数的同时执行该函数,非0:执行; 0:不执行。

线程同步

待续

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值