Linux 多线程编程入门--线程函数解释

Linux线程与互斥详解
本文详细介绍了Linux环境下线程的基本操作,包括线程的创建、退出、等待及线程ID的获取,并深入探讨了如何利用互斥锁解决多线程编程中常见的数据同步问题。

创建线程:
intpthread_create(pthread_t*restrictthread,
constpthread_attr_t*restrictattr,
void*(*start_routine)(void*),void*restrictarg);
参数:
thread输出线程id
attr线程属性, 默认NULL
start_routine线程执行函数
arg线程执行参数
note:函数成功返回0 否则返回错误码
头文件 pthread.h
库文件 pthread
退出线程:
intpthread_exit(void* value_ptr);
参数:
value_ptr线程返回值指针
note: ptrhead_exit()退出调用此函数的线程并释放该线程占用的资源
头文件 pthread.h
库文件 pthread
等待指定线程结束:
intpthread_join(pthread_t thread,void**value_ptr);
参数:
thread一个有效的线程id
value_ptr接收线程返回值的指针
note:调用此函数的线程在指定的线程退出前将处于挂起状态或出现错误而直接返回
如果value_ptr非NULL则value_ptr指向线程返回值的指针
函数成功后指定的线程使用的资源将被释放
头文件 pthread.h
库文件 pthread
获取当前线程id:
pthread_t pthread_self(void);
参数:
note:返回当前函数的id
头文件 pthread.h
库文件 pthread
互斥:
说到多线程,最关心的就是数据访问/改变的同步问题。
windows下有临界区和信号事件等手段来防止多个线程同时读/写同一个数据,那么linux呢?
多线程变成时多使用互斥pthread_mutex_t来起到防止同时访问或改变同一数据.
创建互斥:
intpthread_mutex_init(pthread_mutex_t*restrictmutex,
constpthread_mutexattr_t*restrictattr);
参数:
mutex输出互斥id
attr互斥属性, 默认NULL
note:函数成功返回0 否则返回错误码
头文件 pthread.h
库文件 pthread
锁住互斥:
intpthread_mutex_lock(pthread_mutex_t*mutex);
参数:
mutex互斥id
note:如果指定的互斥id已经被锁住那么呼叫线程在互斥id完全解锁前将
一直处于挂起状态,否则将锁住互斥体
头文件 pthread.h
库文件 pthread
intpthread_mutex_trylock(pthread_mutex_t*mutex);
参数:
mutex互斥id
note:如果指定的互斥id已经被锁住那么将直接返回一个错误,通过判断
此错误来进行不同的处理
头文件 pthread.h
库文件 pthread
解锁互斥:
intpthread_mutex_unlock(pthread_mutex_t*mutex);
参数:
mutex互斥id
note:如果指定的互斥id已经被锁住那么对其解锁
头文件 pthread.h
库文件 pthread
释放互斥:
intpthread_mutex_destroy(pthread_mutex_t*mutex);
参数:
mutex互斥id
note:释放指定的mutex占用的资源
头文件 pthread.h
库文件 pthread
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值