日韩在线免费播放-日韩在线免费av-日韩在线免费-日韩在线毛片-国产高清不卡视频-国产高清不卡

Hi,歡迎來到嵌入式培訓高端品牌 - 華清遠見教育科技集團<北京總部官網(wǎng)>,專注嵌入式工程師培養(yǎng)15年!
當前位置: > 華清遠見教育科技集團 > 嵌入式學習 > 講師博文 > 線程解析(一)
線程解析(一)
時間:2016-12-30作者:華清遠見

在使用線程之前我們要知道線程是個怎樣的概念,它的作用是什么?

在學多進程或多線程編程的時候,有這樣一個概念----進程是資源管理的小單位,線程是程序執(zhí)行的小單位,相對于進程,線程上下文切換花費的開銷更少。因為線程共享了內(nèi)存空間,不同線程可以訪問同一個變量,即多有線程都可以訪問已經(jīng)聲明了的全局變量。在多進程中這種情況需要使用IPC(進程間通信)對象實現(xiàn),這樣增加了額外的開銷,從而降低了性能,并且增加了代碼的復(fù)雜度。

在執(zhí)行方面線程也有著它的優(yōu)勢,因為在創(chuàng)建線程的過程中系統(tǒng)無需復(fù)制內(nèi)存空間和文件描述符等,這樣節(jié)省了很多的cpu時間。

首先我們了解幾個相關(guān)函數(shù)
        pthread_create()創(chuàng)建線程,函數(shù)原型為:
        int pthread_create(pthread_t *restrict thread, const pthread_attr_t *restrict attr, 
        void *(*start_routine)(void*), void *restrict arg);
        thread 返回創(chuàng)建線程的ID,attr是創(chuàng)建線程是設(shè)置的線程屬性。start_routine是線程執(zhí)行體函數(shù),arg為傳遞到線程執(zhí)行體函數(shù)的一個參數(shù)。

下面我們寫一個簡單的多線程的程序。

pthread1.c
        #include <stdio.h>
        #include <pthread.h>

void *thread_a(void *arg)
    {
        printf("thread a enter\n");
    }

void *thread_b(void *arg)
    {
        printf("thread b enter\n");
    }

int main(int argc, char **argv)
    {
        pthread_t tid_a,tid_b;
        int err;
        err = pthread_create(&tid_a,NULL,thread_a,NULL);
        if(err < 0)
        {
            perror("pthread_create thread_a");
        }

err = pthread_create(&tid_b,NULL,thread_b,NULL);
        if(err < 0)
        {
            perror("pthread_create thread_a");
        }
        sleep(5);
        printf("the main close\n");
        return 0;
    }

在這個程序中我們創(chuàng)建了兩個線程分別是tid_a和tid_b,thread_a和thread_b分別是他們的執(zhí)行體。這個時候我們的程序中有了三個線程。因為除了我們常見的兩個線程外,主程序也是一個線程。下面我們嘗試一下傳遞一個參數(shù)到線程執(zhí)行體中。
    pthread2.c
    #include <stdio.h>
    #include <pthread.h>

void *thread_a(void *arg)
    {
        printf("thread a = %d enter\n",*(int *)arg);
    }

void *thread_b(void *arg)
    {
        printf("thread b = %d enter\n", *(int *)arg);
    }

int main(int argc, char **argv)
    {
        pthread_t tid_a,tid_b;
        int err;
        err = pthread_create(&tid_a,NULL,thread_a,(void *)&tid_a);
        if(err < 0)
        {
            perror("pthread_create thread_a");
        }
        printf("create tid_a = %d\n",tid_a);
        err = pthread_create(&tid_b,NULL,thread_b,(void *)&tid_b);
        if(err < 0)
        {
            perror("pthread_create thread_a");
        }
        printf("create tid_b = %d\n",tid_b);
        sleep(5);
        printf("the main close\n");
        return 0;
    }

發(fā)表評論
評論列表(網(wǎng)友評論僅供網(wǎng)友表達個人看法,并不表明本站同意其觀點或證實其描述)
主站蜘蛛池模板: 毛骨悚然撞鬼经| 打开双腿扒开打屁股羞辱惩罚视频 | 婴儿睡眠时间对照表| 蜜桃成熟时在线看| 免费完整版在线观看| 北京卫视今晚的电视剧是什么| 爱欲1990未删减版播放| 速度与激情9| 影音先锋欧美| 漂亮的女邻居5伦理| 刘德华神雕侠侣| 美女的咪咪| 小敏的迦南诗歌大全| 高奇| 张成楚| 双世宠妃1| bobo视频| 《遇见你之后》电影在线观看| cgtn news在线直播| 画魂缠身 电影| a b a b四字成语| 变形金刚2演员表| 复制情人之意识转移| 黄色网大全| 吴添豪| 隐藏的秘密电影免费观看全集| 大侠霍元甲演员表| 章若楠高清壁纸| 相识韩国| 好好歌词| 手机号大全| 战长沙剧情介绍| 丁尼| 楚青丝完美人生免费阅读| 南海长城 电影| 永夜星河演员| 壁纸超清全屏| 羞羞的铁拳高清免费观看完整版| 天下第一楼演员表全部| 电影《年龄差》| 动漫秀场|