Thread Suspension

Sometimes create another thread in a thread, the main thread to wait until the return of the thread creation, capture the return value of the thread after the exit, this time on the need to thread suspension.

 

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

pthread_join spent function suspends the current thread until th specified thread terminates.

/***
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;
}

operation result:

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

 

The main function has been created with a thread of execution to wait for completion, and get the return value of the thread execution ended.

 

problem:

Malloc function is allocated heap space, how to return a stack space in the {}. Doubtful.

Guess you like

Origin www.cnblogs.com/wanghao-boke/p/11262635.html