線程掛起


有時候在一個線程中創建了另外一個線程,主線程要等到創建的線程返回了,獲取該線程的返回值后才退出,這個時候就需要把線程掛起。

 

int pthread_join(pthread_t th,void ** thr_return);

pthread_join函數用去掛起當前線程,直至th指定的線程終止為止。

/***
hangup.c
***/
#include<stdio.h>
#include<pthread.h>
#include<errno.h>
#include<string.h>
#include<stdlib.h>

void * func(void *arg)
{
    int i = 0;
    for(; i < 5; i++)
    {
        printf("func run %d\n",i);
        sleep(1);
    }
    int *p = (int *)malloc(sizeof(int));
    *p = 11;
    return p;
}

int main()
{
    pthread_t t1;
    int err = pthread_create(&t1,NULL,func,NULL);
    if( 0 != err)
    {
        printf("thread_create failled : %s\n",strerror(errno));
    }
    else
    {
        printf("thread_create success\n");
    }
    void *p = NULL;
    pthread_join(t1,&p);
    printf("thread exit : code = %d\n",*(int *)p);
    return EXIT_SUCCESS;
}

運行結果:

exbot@ubuntu:~/wangqinghe/thread/20190729$ gcc hangup.c -o hangup -lpthread

exbot@ubuntu:~/wangqinghe/thread/20190729$ ./hangup

thread_create success

func run 0

func run 1

func run 2

func run 3

func run 4

thread exit : code = 11

 

主函數一直帶等待創建的線程執行完畢,並得到線程執行結束的返回值。

 

問題:

函數中malloc分配的是堆空間,如何返回個{}中的棧空間的。存疑。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM