Chinaunix首页 | 论坛 | 博客
  • 博客访问: 279590
  • 博文数量: 109
  • 博客积分: 2116
  • 博客等级: 大尉
  • 技术积分: 1062
  • 用 户 组: 普通用户
  • 注册时间: 2009-10-22 15:38
文章分类

全部博文(109)

文章存档

2013年(2)

2011年(16)

2010年(90)

2009年(1)

我的朋友

分类: 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;

}

编译运行结果如下:

通过free命令查看内存使用情况,可以发现线程结束收回系统资源,实现分离属性。
阅读(378) | 评论(0) | 转发(0) |
0

上一篇:线程基础编程

下一篇:线程互斥锁

给主人留下些什么吧!~~