多線程編程之:Linux線程編程
(3)使用實(shí)例。
下面的實(shí)例是在我們已經(jīng)很熟悉的實(shí)例的基礎(chǔ)上增加線程屬性設(shè)置的功能。為了避免不必要的復(fù)雜性,這里就創(chuàng)建一個(gè)線程,這個(gè)線程具有綁定和分離屬性,而且主線程通過(guò)一個(gè)finish_flag標(biāo)志變量來(lái)獲得線程結(jié)束的消息,而并不調(diào)用pthread_join()函數(shù)。
/*thread_attr.c*/
#include stdio.h>
#include stdlib.h>
#include pthread.h>
#define REPEAT_NUMBER 3 /* 線程中的小任務(wù)數(shù) */
#define DELAY_TIME_LEVELS 10.0 /* 小任務(wù)之間的最大時(shí)間間隔 */
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));
/* 初始化線程屬性對(duì)象 */
res = pthread_attr_init(attr);
if (res != 0)
{
printf(Create attribute failedn);
exit(res);
}
/* 設(shè)置線程綁定屬性 */
res = pthread_attr_setscope(attr, PTHREAD_SCOPE_SYSTEM);
/* 設(shè)置線程分離屬性 */
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);
}
/* 釋放線程屬性對(duì)象 */
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相關(guān)文章:linux教程
評(píng)論