linux线程属性
来源:互联网 发布:淘宝网找工作 编辑:程序博客网 时间:2024/05/20 00:15
pthread_create()函数的第二个参数(pthread_attr_t *attr)表示线程的属性,在以前的例子中将其值设为NULL,也就是采用默认属性,线程的多项属性都是可以修改的,这些属性包括绑定属性,分离属性,堆栈属性,堆栈大小,优先级。系统默认的是非绑定,非分离,缺省1M的堆栈以及父子进程优先级相同。
(1)绑定属性
linux中采用一对一的线程机制,也就是一个用户线程对应一个内核线程,绑定属性就是指一个用户线程固定的分配给一个内核线程,cpu的时间片的调度是面向内核线程的(也就是轻量级进程),所以具有绑定属性的线程可以保证在需要的时候总有一个内核线程与之对应,非绑定属性就是指用户线程和内核线程的关系不是始终固定的,有系统控制分配的。
(2)分离属性
分离属性用来决定一个线程用什么样的方式终止自己,在非分离的情况下,当一个线程终止时他的系统资源并没有被释放,也就是没有真正的终止,只有当pthread_join()返回时创建的线程才能释放自己占用的系统资源,而在分离属性属性情况下,一个线程结束时立即释放他锁占用的系统资源,
ps:如果设置了一个线程的分离属性,而这个线程运行非常快的话,可能在pthread_create()返回前就终止了,此时他的线程号和系统资源就分配给了别的线程,此时调用pthread_create()获得的线程号就是错误的。
pthread_attr_init():初始化线程属性结构体
pthread_attr_destroy():对分配的属性结构指针进行清理和回收
pthread_attr_setscope():设置绑定属性
pthread_attr_setdetachstate():设置线程分离属性
pthread_attr_getschedparam():获取线程优先级
pthread_attr_setschedparam():设置线程优先级
当设置好这些属性之后就可以调用pthread_create()创建线程了
pthread_attr_init()函数语法:
pthread_attr_setscope()函数语法:
pthread_attr_setdetachstate()函数语法:
pthread_attr_getschedparam():
pthread_attr_setschedparam():
#include <stdlib.h>
#include <pthread.h>
#define REPEAT_NUMBER 3
#define DELAY_TIME_LEVELS 10.0
int finish_flag = 0 ;
void *thrd_func(void *arg)
{
int delay_time = 0 ;
int count = 0 ;
printf("thread is starting\n") ;
for (count = 0; count < REPEAT_NUMBER; count++)
{
delay_time = (int)(rand() * DELAY_TIME_LEVELS/(RAND_MAX)) + 1;
sleep(delay_time) ;
printf("\tThread job %d delay = %d\n", count, delay_time) ;
}
printf("thread finished\n") ;
finish_flag = 1 ;
pthread_exit(NULL) ;
}
int main()
{
pthread_t thread ;
pthread_attr_t attr ;//线程属性结构体
int no = 0, res ;
void *thrd_ret ;
srand(time(NULL)) ;
res = pthread_attr_init(&attr) ;//初始化结构体
if (res != 0)
{
printf("create attribute failed\n") ;
exit(res) ;
}
res = pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM) ;//设置绑定属性
res += pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) ;//设置分离属性
if (res != 0)
{
printf("setting attribute failed\n") ;
exit(res) ;
}
res = pthread_create(&thread, &attr, thrd_func, NULL) ;
if (res != 0)
{
printf("create thread %d failed\n", no) ;
exit(res) ;
}
pthread_attr_destroy(&attr) ;//释放线程属性对象
printf("create threads success\n") ;
while(!finish_flag)
{
printf("waitting for thread to finish...\n") ;
sleep(2) ;
}
return 0 ;
}
程序运行前:
程序运行中:
程序运行后:
问题:主要看这个used选项的情况,但发现这个程序运行前后used不一样呀,这是个问题,我不知道为什么???
本来应该是一样的,才能说明占用的内存被成功释放了。
- linux 线程 线程属性
- linux线程属性、共享属性
- linux 线程编程:线程属性
- Linux线程属性总结
- Linux线程属性总结
- Linux 线程设置属性
- linux线程属性
- Linux线程属性总结
- linux线程属性
- Linux线程属性总结
- Linux线程属性总结
- Linux线程属性
- Linux线程属性
- linux线程的属性
- Linux线程属性总结
- Linux - 线程属性控制
- linux线程属性设置
- linux多线程-线程属性
- VIM显示utf-8乱码
- HDU4474
- 设计模式六大原则(1):单一职责原则SRP(Single Responsibility Principle)
- The connection to adb is down, and a severe error has occured.
- 各种排序方法总结
- linux线程属性
- ocx开发经验
- php.ini 中的short_open_tag和asp_tags
- android 布局:两端对齐中间填充
- MyEclipse的快捷键
- jQuery、Ajax、PHP、Json的一个综合例子
- javascript性能提升——减少访问DOM的次数
- 迅雷近几年笔试题及其分析
- Android中webview和js之间的交互