多线程编程之:Linux线程编程
(3)使用实例。
下面的实例是在我们已经很熟悉的实例的基础上增加线程属性设置的功能。为了避免不必要的复杂性,这里就创建一个线程,这个线程具有绑定和分离属性,而且主线程通过一个finish_flag标志变量来获得线程结束的消息,而并不调用pthread_join()函数。
/*thread_attr.c*/
#include stdio.h>
#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 startingn);
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 = %dn, count, delay_time);
}
printf(Thread finishedn);
finish_flag = 1;
pthread_exit(NULL);
}
int main(void)
{
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 failedn);
exit(res);
}
/* 设置线程绑定属性 */
res = pthread_attr_setscope(attr, PTHREAD_SCOPE_SYSTEM);
/* 设置线程分离属性 */
res += pthread_attr_setdetachstate(attr, PTHREAD_CREATE_DETACHED);
if (res != 0)
{
printf(Setting attribute failedn);
exit(res);
}
res = pthread_create(thread, attr, thrd_func, NULL);
if (res != 0)
{
printf(Create thread failedn);
exit(res);
}
/* 释放线程属性对象 */
pthread_attr_destroy(attr);
printf(Create tread successn);
while(!finish_flag)
{
printf(Waiting for thread to finish...n);
sleep(2);
}
return 0;
}
linux操作系统文章专题:linux操作系统详解(linux不再难懂)linux相关文章:linux教程
评论