中文字幕 另类精品,亚洲欧美一区二区蜜桃,日本在线精品视频免费,孩交精品乱子片免费

<sup id="3hn2b"></sup>

    1. <sub id="3hn2b"><ol id="3hn2b"></ol></sub><legend id="3hn2b"></legend>

      1. <xmp id="3hn2b"></xmp>

      2. 新聞中心

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

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

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


        本文引用地址:http://www.antipu.com.cn/article/257101.htm

        (4)使用實(shí)例。

        在前面已經(jīng)通過互斥鎖同步機(jī)制實(shí)現(xiàn)了多線程的順序執(zhí)行。下面的例子是用信號(hào)量同步機(jī)制實(shí)現(xiàn)3個(gè)線程之間的有序執(zhí)行,只是執(zhí)行順序是跟創(chuàng)建線程的順序相反。


        /*thread_sem.c*/

        #include stdio.h>

        #include stdlib.h>

        #include pthread.h>

        #include semaphore.h>


        #define THREAD_NUMBER 3 /* 線程數(shù) */

        #define REPEAT_NUMBER 3 /* 每個(gè)線程中的小任務(wù)數(shù) */

        #define DELAY_TIME_LEVELS 10.0 /*小任務(wù)之間的最大時(shí)間間隔*/

        sem_t sem[THREAD_NUMBER];


        void *thrd_func(void *arg)

        {

        int thrd_num = (int)arg;

        int delay_time = 0;

        int count = 0;

        /* 進(jìn)行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);

        /* 對最后創(chuàng)建的線程的信號(hào)量進(jì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);

        }

        /* 進(jìn)行V操作 */

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

        }


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

        {

        /* 刪除信號(hào)量 */

        sem_destroy(sem[no]);

        }


        return 0;

        }

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

        linux相關(guān)文章:linux教程




        評(píng)論


        相關(guān)推薦

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

        關(guān)閉