Chinaunix首页 | 论坛 | 博客
  • 博客访问: 655596
  • 博文数量: 516
  • 博客积分: 4119
  • 博客等级: 上校
  • 技术积分: 4288
  • 用 户 组: 普通用户
  • 注册时间: 2012-10-30 17:29
文章分类

全部博文(516)

文章存档

2014年(4)

2013年(160)

2012年(352)

分类:

2012-11-01 11:23:38

一.函数:

1.线程属性的初始化与销毁:
#include
int pthread_attr_init(pthread_attr_t *attr);
int pthread_attr_destroy(pthread_attr_t   *attr);

Both return: 0 if OK, error number on failure
2.设置线程属性--detackstate(分离状态):
#include
int pthread_attr_getdetachstate(const pthread_attr_t *restrict attr, int *detachstate);
int pthread_attr_setdetachstate(pthread_attr_t *attr,  int detachstate);

Both return: 0 if OK, error number on failure
detachstate有两个选项:PTHREAD_CREATE_DETACHED 分离状态启动线程
                       PTHREAD_CREATE_JOINABLE 正常状态启动线程
3.设置线程属性--stackaddr(线程栈的最低地址),stacksize(线程栈的大小):
#include
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);

Both return: 0 if OK, error number on failure
4.设置线程属性--stacksize(线程栈的大小):
#include
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);

Both return: 0 if OK, error number on failure
5.设置线程属性--guardsize(线程栈末尾的警戒缓冲区大小)
#include
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); 

Both return: 0 if OK, error number on failure
二.重点:

三.例子:

以分离状态创建线程

  1. #include   
  2. #include   
  3. #include   
  4.   
  5. void * thr_fn()  
  6. {  
  7.     printf("thread run\n");  
  8.     pthread_exit((void *)0);  
  9. }  
  10.   
  11. int main()  
  12. {  
  13.     pthread_t tid;  
  14.     pthread_attr_t attr;  
  15.     int ret;  
  16.   
  17.     ret = pthread_attr_init(&attr);  
  18.     if(ret!=0)  
  19.         printf("init attr error:%s\n",strerror(ret));  
  20.     ret = pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);  
  21.     if(ret==0)  
  22.     {  
  23.         ret = pthread_create(&tid,&attr,thr_fn,NULL);  
  24.         if(ret!=0)  
  25.             printf("create thread error:%s\n",strerror(ret));  
  26.     }  
  27.     pthread_attr_destroy(&attr);  
  28.     sleep(1);  
  29.     return 0;  
  30. }  
运行:
root@ubuntu1:~/12# ./a.out
thread run
阅读(507) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~