線程 pthread_create Linux函數 線程建立

來源:互聯網
上載者:User

線程:是在某個進程中被建立的,而它達到生命週期都在這個進程中。

線程它允許一個進程執行一個或多個執行路徑(即1個進程可以有多個線程,來執行不同的程式),這些執行路徑由系統非同步調度。

進程有自己的資料區段,程式碼片段,堆棧段。

而線程與進程的區別:

1.       程式碼片段一樣

2.資料區段一樣(全域變數)。

3.棧堆段不一樣!!!!!

建立線程的函數:

#include<pthread.h>

int  pthread_create(pthread_t*thread,pthread_attr_t   *attr,

void * (*start_routine)(void *arg),

void *arg);

功能:建立線程

傳回值:成功0

thread :程式的ID(標示符)。

attr:線程的屬性設定,如果為NULL,則建立系統預設的線程屬性。

start_routine:線程運行函數的起始地址。

最後一個參數是:線程運行函數的參數。

例子:

#include<stdio.h>

#include<pthread.h>

#include<stdlib.h>

void *thfun(void *arg)

{                    printf("new  thread!\n");

       printf("%s\n",(char*)arg);

        return ((void *)0);

}

int main(int argc ,char *argv[])

{

       int ret;

       pthread_t pthid;

       ret=pthread_create(&pthid,NULL,thfun,(void *)"hello");

      // 第一個參數為線程ID,把它儲存在pthid中。

       //If attr is NULL, the default attributes shall be used.

       //第二個參數if是NULL,則建立預設屬性的進程。

      // 。。。3。。線程運行函數的起始地址,

      //..... 4.... 線程運行函數的參數。

  If(ret!=1){

      perror("can'tcreat thread ");

exit(EXIT_FAILURE);

}  

       printf("main thread!\n");

        sleep(1);

       exit(0);//return 0;

}

 

 

運行結果:

下面我們看個例子:

#include<stdio.h>

#include<stdlib.h>

 #include<pthread.h>

void *th_fun(void*arg)

{

        printf("%s",arg);//列印傳遞的參數

        while(1)

                fputs("new thread \n",stdout);

//輸出字串new thread到標準輸出

        return ((void*)0);

}

int main()

{

        int ret;

        pthread_t tid;

       if((ret=pthread_create(&tid,NULL,th_fun,"new thread  created!\n"))==-1)

        {

                perror("pthread_createerror ");

                exit(EXIT_FAILURE);

        }

        while(1)

                fputs("main  thread \n",stdout);

//輸出字串main  thread到標準輸出

        return 0;

}

運行結果:

我們從運行結果來看,它一會輸出main thread ,一會輸出new thread

可以看出系統是對兩個線程進行調度。

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.