posix thread介绍
来源:互联网 发布:锻造模拟软件 forging 编辑:程序博客网 时间:2024/06/05 14:55
posix thread是操作系统级(OS level)的API规范,主要用来定义线程及线程间同步的相关操作,采用C语言定义。posix规范主要在unix like类系统上实现;Windows类系统采用了自己的线程API。目前很多语言都在其标准库中提供了语言级的线程支持:如Java中的Thread,concurrenty包;python中的threading model;C++11标准中的thread库等。还有很多以第三方库方式提供的各种语言的线程实现,就不一一列举了。
线程环境要素
定义一个完整的线程环境需要一下几个方面:
执行环境 execution context
即线程的表示,生命周期的管理等。
调度 scheduling
决定线程的运行状态。
同步 synchronization
多个线程之间运行时序的控制。
本文介绍下posix thread中对上述几个方面的设计与实现。
执行环境
线程的表示
posix中用pthread_t类型表示一个线程。
生命周期管理 lifecycle
线程创建 creating:
int pthread_create(pthread_t *restrict thread, const pthread_attr_t *restrict attr, void *(*start_routine)(void*), void *restrict arg);线程终止 terminating:
void pthread_exit(void *value_ptr);
int pthread_cancel(pthread_t thread);
自然终止
当线程的入口函数(start_routine)返回时,线程自然退出。
等待线程终止
int pthread_join(pthread_t thread, void **value_ptr);线程回收recycling
int pthread_detach(pthread_t thread);
这个函数的使用需要结合线程创建时的属性(attribute)设置。
调度
由操作系统内核实现(用户空间的线程实现除外),根据不同的调度策略,调度个进程的运行。posix创建线程时,可以指定优先级参数,来设定线程的调度状态。
同步
同步涉及两种情况:互斥和协同工作。
互斥mutual exclusion,race condition
用来保证多个线程对共享资源(shared resource)的操作的一致性。posix thread提供的机制:mutex和reader/writer lock
mutex:
pthread_mutex_t表示一个mutex
int pthread_mutex_init ( pthread_mutex_t *mutex, const pthread_mutexattr_t *attr);
int pthread_mutex_destroy ( pthread_mutex_t *mutex);
int pthread_mutex_lock (pthread_mutex_t *mutex);
int pthread_mutex_trylock (pthread_mutex_t *mutex);
int pthread_mutex_unlock (pthread_mutex_t *mutex);
reader/writer lock
The read-write lock permits concurrent reads and exclusive writes to a protected resource.
目前很多OS上没有实现 reader/writer lock。r/w的实现可以结合mutext和condition自行实现。
具体可参考:
http://docs.oracle.com/cd/E19455-01/806-5257/6je9h032m/index.html
协同工作 cooperating
不同线程之间根据某个事件,来决定执行。代表的情况有: producer/consumer,3哲学家问题等。posix thread提供的机制:Condition Variables
pthread_cond_t:表示一个条件变量
pthread_cond_init( )
pthread_cond_destroy( )
pthread_cond_broadcast( )
pthread_cond_signal( )
pthread_cond_timedwait( )
pthread_cond_wait( )
posix thread的设计简洁,完备,抽象清晰、合理,是API设计的典范。posix thread提供的机制也比较简单,使用这些机制可以构建复杂的多线程程序。深入理解这些机制本身非常重要(编写正确程序的前提),所有的线程实现中(包括语言级和系统级)的基本概念和posix thread中的也都是一致的。
0 0
- posix thread介绍
- POSIX thread
- posix thread
- apue thread posix thread posix线程相关
- YoLinux Tutorial: POSIX thread
- POSIX Thread相关
- pthread_mutexattr --POSIX THREAD
- POSIX thread (pthread) 简介
- POSIX thread (pthread) libraries
- POSIX thread (pthread) libraries
- POSIX thread (pthread) 简介
- POSIX thread (pthread) libraries
- POSIX thread API
- POSIX thread (pthread) libraries
- Posix thread 多线程编程
- Linux Posix Thread Programming
- POSIX thread (pthread) 简介
- POSIX thread (pthread) libraries
- div 实现长英文字母自动换行CSS
- 看大师讲解移动互联网前端开发流程
- 我的小程序
- Android EditText文本框重新获得焦点和输入完成后的检查事件触发
- 1076. Forwards on Weibo
- posix thread介绍
- 夏令营Sw为什注射删除俺
- 如果北航的地方慢慢两年装
- 僬潜赴郝弛亟膳环猜忠势蹬继戮饲
- cctv5
- mac下创建bash_profile步骤
- 使用XMPP集成unieap做B/S版聊天软件
- windows installer出错信息解决方法
- java 基础