pthread_join pthread_exit 線程 Linux函數 線程退出 線程等待

來源:互聯網
上載者:User

接下來我們看一下線程退出函數和等待函數。

 #include <pthread.h>

       void pthread_exit(void *value_ptr);

value_ptr:是線程的傳回值。有pthread_join()檢測獲得。

功能:線程退出

#include<pthread.h>

       int pthread_join(pthread_t thread, void**value_ptr);

功能:等待指定的線程結束。

傳回值:成功返回0

參數:

thread:等待線程的ID(標示符)

value_ptr:使用者自訂的指標,用來儲存被等待線程的傳回值。

這個函數是線程阻塞函數,調用它的函數將一直阻塞到被等待的線程結束為止,當函數傳回值,被等待線程的資源被回收。

我們看個例子:

#include<stdio.h>

#include<stdlib.h>

 

void *th_fun1(void*arg)

{

        int i=10/2;

        printf("%s",arg);

        while(i-->0)

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

        pthread_exit ((void*)1);

}

 

void *th_fun2(void*arg)

{

        int i=10/2;

        printf("%s",arg);

        while(i-->0)

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

pthread_exit((void*)2);

}

 

int main()

{

        int ret;

        pthread_t tid1,tid2;

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

        {

                perror("pthread_createerror ");

                exit(EXIT_FAILURE);

        }

       if((ret=pthread_create(&tid2,NULL,th_fun2,"new thread 2  created!\n"))==-1)

        {

                perror("pthread_createerror ");

                exit(EXIT_FAILURE);

        }

        void *fret1;

void *fret2;

        pthread_join(tid1,&fret1);

        pthread_join(tid2,&fret2);

    printf("fret1=%d\n",(int)fret1);

    printf("fret2=%d\n",(int)fret2);

        return 0;

}

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.