POSIX线程机制定义了多种数据类型,这些数据类型对应用程序来说其内部结构是不透明的。就是说直接访问它们的数据对象是无意义的,而应该使用pthreads(7)库定义的方法去进行访问。各种数据类型对象方法的动作包括初始化、销毁、读取、更改等。
1、线程属性对象
A.初始化和去初始化
在使用线程属性对象之前,应该使用对其进行初始化,如果已经使用结束,应销毁此对象以释放进程空间:
1
2
3
4
| #include <pthread.h>
int pthread_attr_init(pthread_attr_t *attr);
int pthread_attr_destroy(pthread_attr_t *attr); |
B.分离属性
下面的函数用于读取和设置线程的分离属性:
1
2
3
4
| #include <pthread.h>
int pthread_attr_getdetachstate(const pthread_attr_t *restrict attr, int *detachstate);
int pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate); |
线程的分离属性只有两个选项。为PTHREAD_CREATED_JOINABLE时,线程退出时需要另外一个线程使用pthread_join(3)来回收线程资源。为PTHREAD_CREATED_DETACHED时,线程退出时不需要join。
C.栈属性
线程使用栈地址和栈大小这两个属性来描述线程使用的栈。读/写线程栈属性的函数为
1
2
3
4
| #include <pthread.h>
int pthread_attr_getstack(const pthread_attr_t *restrict attr, void **restrict stackaddr, size_t *restrict stacksize);
int pthread_attr_setstack(const pthread_attr_t *attr, void *stackaddr, size_t *stacksize); |
系统将参数中的线程栈地址定义为线程栈的最低地址空间。还可以使用以下函数单独设置线程的栈大小属性:
1
2
3
4
| #include <pthread.h>
int pthread_attr_getstacksize(const pthread_attr_t *restrict attr, size_t *restrict stacksize);
int pthread_attr_setstacksize(pthread_attr_t *attr, size_t stacksize); |
D.栈警戒区
栈警戒区在线程栈空间末尾之后,在线程空间溢出到警戒区时,线程将收到信号通知(一般是SIGSEGV)。栈警戒区的默认大小为PAGESIZE,如果自行定义了任何线程属性,但不修改线程的警戒区属性,则警戒区大小将被置零。
设置和修改栈警戒区属性的函数为:
1
2
3
4
| #include <pthread.h>
int pthread_attr_getguardsize(const pthread_attr_t *restrict attr, size_t *restrict guardsize);
int pthread_attr_setguardsize(pthread_attr_t *attr, size_t guardsize); |
E.未定义在pthread_attr_t中的线程属性
主要包括取消选项以及并发度选项。并发度描述了应用程序线程可映射的内核线程数,即对于用户程序,最多可以有多少个线程可以“同时”执行系统调用,在操作系统实现为一个内核线程只映射为一个用户进程时,并发度的提高有助于改善程序性能。
1
2
3
4
| #include <pthread.h>
int pthread_getconcurrency(void);
int pthread_setconcurrency(int level); |
在未设置并发度时,pthread_getconcurrency将返回0。pthread_setconcurrency的设置值不一定会被内核接受,而当参数为0时,将取消之前一次pthread_setconcurrency的设置,而让内核自行调度。
[更多...]