新聞中心

        EEPW首頁 > 嵌入式系統(tǒng) > 設(shè)計應(yīng)用 > 多線程編程之:Linux線程編程

        多線程編程之:Linux線程編程

        作者: 時間:2013-09-13 來源:網(wǎng)絡(luò) 收藏


        本文引用地址:http://www.104case.com/article/257101.htm

        (3)使用實例。

        下面的實例是在我們已經(jīng)很熟悉的實例的基礎(chǔ)上增加線程屬性設(shè)置的功能。為了避免不必要的復(fù)雜性,這里就創(chuàng)建一個線程,這個線程具有綁定和分離屬性,而且主線程通過一個finish_flag標(biāo)志變量來獲得線程結(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ù)之間的最大時間間隔 */

        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);

        }

        /* 設(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 = (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相關(guān)文章:linux教程




        評論


        相關(guān)推薦

        技術(shù)專區(qū)

        關(guān)閉
        主站蜘蛛池模板: 曲沃县| 武义县| 正镶白旗| 丹巴县| 黔江区| 英山县| 那曲县| 石首市| 本溪市| 九寨沟县| 仙游县| 称多县| 鄂尔多斯市| 深水埗区| 平远县| 吉首市| 江城| 临猗县| 锦州市| 托克托县| 开封市| 当阳市| 龙井市| 琼海市| 渝北区| 宁乡县| 盐池县| 读书| 甘洛县| 绥中县| 凤庆县| 文成县| 家居| 六安市| 大港区| 炎陵县| 江津市| 昌江| 辽中县| 竹溪县| 当阳市|