分类: LINUX
2010-07-09 14:42:53
默认的线程属性设置为NULL, 但是事实上线程有很多可以更改的属性,比如:绑定属性,分离属性,堆栈地址,堆栈大小以及优先级。
流程为:首先调用pthread_attr_init进行初始化,然后进行设置(设置函数主要有:绑定pthread_attr_setcope, 分离pthread_attr_setdetachstate, 优先级pthread_attr_getchedparam, pthread_attr_setschedparam等),最后调用pthread_attr_destory进行回收。
设置完成就可以调用pthread_create创建线程了。
下面实例源代码来自华清远见:
#include
#include
#include
#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(void)
{
pthread_t thread;
pthread_attr_t attr;
int res;
srand(time(NULL));
res = pthread_attr_init(&attr);//初始化线程属性对象
if(res != 0)
{
printf("Creat 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("Creat thread failed!\n");
exit(res);
}
pthread_attr_destroy(&attr);//释放线程属性对象
printf("Creat thread success!\n");
while(!finish_flag)
{
printf("Waiting for thread to finish...\n");
sleep(2);
}
return 0;
}
编译运行结果如下: