一.函数:
1.线程属性的初始化与销毁:#include <pthread.h>
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 <pthread.h>
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 <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);
Both return: 0 if OK, error number on failure
4.设置线程属性--stacksize(线程栈的大小):
#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);
Both return: 0 if OK, error number on failure
5.设置线程属性--guardsize(线程栈末尾的警戒缓冲区大小)
#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);
Both return: 0 if OK, error number on failure
二.重点:
三.例子:
以分离状态创建线程
- #include <stdio.h>
- #include <pthread.h>
- #include <string.h>
- void * thr_fn()
- {
- printf("thread run\n");
- pthread_exit((void *)0);
- }
- int main()
- {
- pthread_t tid;
- pthread_attr_t attr;
- int ret;
- ret = pthread_attr_init(&attr);
- if(ret!=0)
- printf("init attr error:%s\n",strerror(ret));
- ret = pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
- if(ret==0)
- {
- ret = pthread_create(&tid,&attr,thr_fn,NULL);
- if(ret!=0)
- printf("create thread error:%s\n",strerror(ret));
- }
- pthread_attr_destroy(&attr);
- sleep(1);
- return 0;
- }
#include <stdio.h> #include <pthread.h> #include <string.h> void * thr_fn() { printf("thread run\n"); pthread_exit((void *)0); } int main() { pthread_t tid; pthread_attr_t attr; int ret; ret = pthread_attr_init(&attr); if(ret!=0) printf("init attr error:%s\n",strerror(ret)); ret = pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED); if(ret==0) { ret = pthread_create(&tid,&attr,thr_fn,NULL); if(ret!=0) printf("create thread error:%s\n",strerror(ret)); } pthread_attr_destroy(&attr); sleep(1); return 0; }运行:
root@ubuntu1:~/12# ./a.out
thread run