多線程編程之:Linux線程編程
(3)使用實例。
下面的實例是在我們已經(jīng)很熟悉的實例的基礎上增加線程屬性設置的功能。為了避免不必要的復雜性,這里就創(chuàng)建一個線程,這個線程具有綁定和分離屬性,而且主線程通過一個finish_flag標志變量來獲得線程結束的消息,而并不調(diào)用pthread_join()函數(shù)。
/*thread_attr.c*/
#include stdio.h>
#include stdlib.h>
#include pthread.h>
#define REPEAT_NUMBER 3 /* 線程中的小任務數(shù) */
#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操作系統(tǒng)文章專題:linux操作系統(tǒng)詳解(linux不再難懂)linux相關文章:linux教程
評論