新聞中心

        EEPW首頁 > 嵌入式系統 > 設計應用 > 多線程編程之:Linux線程編程

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

        作者: 時間:2013-09-13 來源:網絡 收藏


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

        (4)使用實例。

        在前面已經通過互斥鎖同步機制實現了多線程的順序執行。下面的例子是用信號量同步機制實現3個線程之間的有序執行,只是執行順序是跟創建線程的順序相反。


        /*thread_sem.c*/

        #include stdio.h>

        #include stdlib.h>

        #include pthread.h>

        #include semaphore.h>


        #define THREAD_NUMBER 3 /* 線程數 */

        #define REPEAT_NUMBER 3 /* 每個線程中的小任務數 */

        #define DELAY_TIME_LEVELS 10.0 /*小任務之間的最大時間間隔*/

        sem_t sem[THREAD_NUMBER];


        void *thrd_func(void *arg)

        {

        int thrd_num = (int)arg;

        int delay_time = 0;

        int count = 0;

        /* 進行P操作 */

        sem_wait(sem[thrd_num]);

        printf(Thread %d is startingn, thrd_num);


        for (count = 0; count  REPEAT_NUMBER; count++)

        {

        delay_time = (int)(rand() * DELAY_TIME_LEVELS/(RAND_MAX)) + 1;

        sleep(delay_time);

        printf(tThread %d: job %d delay = %dn,

        thrd_num, count, delay_time);

        }


        printf(Thread %d finishedn, thrd_num);

        pthread_exit(NULL);

        }


        int main(void)

        {

        pthread_t thread[THREAD_NUMBER];

        int no = 0, res;

        void * thrd_ret;


        srand(time(NULL));

        for (no = 0; no  THREAD_NUMBER; no++)

        {

        sem_init(sem[no], 0, 0);

        res = (thread[no], NULL, thrd_func, (void*)no);

        if (res != 0)

        {

        printf(Create thread %d failedn, no);

        exit(res);

        }

        }


        printf(Create treads successn Waiting for threads to finish...n);

        /* 對最后創建的線程的信號量進行V操作 */

        sem_post(sem[THREAD_NUMBER - 1]);

        for (no = THREAD_NUMBER - 1; no >= 0; no--)

        {

        res = pthread_join(thread[no], thrd_ret);

        if (!res)

        {

        printf(Thread %d joinedn, no);

        }

        else

        {

        printf(Thread %d join failedn, no);

        }

        /* 進行V操作 */

        sem_post(sem[(no + THREAD_NUMBER - 1) % THREAD_NUMBER]);

        }


        for (no = 0; no  THREAD_NUMBER; no++)

        {

        /* 刪除信號量 */

        sem_destroy(sem[no]);

        }


        return 0;

        }

        linux操作系統文章專題:linux操作系統詳解(linux不再難懂)

        linux相關文章:linux教程




        評論


        相關推薦

        技術專區

        關閉
        主站蜘蛛池模板: 克东县| 凌海市| 玉山县| 齐齐哈尔市| 顺昌县| 威信县| 梓潼县| 耒阳市| 法库县| 德庆县| 什邡市| 临邑县| 扬中市| 安福县| 宁津县| 克山县| 黎城县| 吉隆县| 舞钢市| 徐水县| 田林县| 视频| 炎陵县| 南华县| 文成县| 西藏| 九龙坡区| 诏安县| 昆明市| 棋牌| 余姚市| 长泰县| 商河县| 双峰县| 习水县| 寿光市| 肇州县| 宁武县| 都安| 吉首市| 福建省|