Thread recovery

* Void pthread_exit (void retval) the introduction of a single thread ;:

Contrast: exit (): Process Exit
difference of the following three:
(1) Exit (): the whole process exits;
(2) pthread_exit (): the current thread exits;
(3) return: return to the caller where to go;

pthread_join int ** (pthread_t the Thread, void retval): waiting thread exit

Contrast: wait wait for the child process exits blocked

Exit single thread

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
#include<string.h>
typedef struct{
        char c;
        int a;
        char * ch[64];
}exit_t;

void *pthread_fun(void *arg)
{ 
        exit_t * retval = (exit_t *)arg;

        retval->c='m';
        retval->a=10;
        strcpy(retval->ch,"hello world\n");
        pthread_exit((void *)10);

}
int main()
{
        pthread_t tid;
        int ret;
        exit_t * retval;

        ret = pthread_create(&tid,NULL,pthread_fun,(void *)retval);
        if(ret != 0)
        {
                printf("ptthread_cretea error");
                exit(1);
        }
        sleep(1);
        printf("c=%c   a = %d   ch=%s\n",retval->c,retval->a,retval->ch);

        int *pv;
        pthread_join(tid,(void **)&pv );
        printf("pv=%d\n",(int)pv);
        return 0;
}

Recycling multiple threads

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
#include<string.h>

void *pthread_fun(void *arg)
{
        int i= (int) arg;
        sleep(i);
        printf("%dth tid=%d\n",i+1,pthread_self());
        pthread_exit((void *)i);
}
int main()
{
        pthread_t tid[5];
        int ret,i;

        for(i = 0; i<5; ++i)
        {
                ret = pthread_create(&tid[i],NULL,pthread_fun,(void *)i);
                if(ret != 0)
                {
                        printf("ptthread_cretea error");
                        exit(1);
                }
        }


        for(i = 0; i<5; ++i)
        {
                int * retval;
                pthread_join(tid[i],(void **)&retval);
                printf("%dth finish\n ",(int)retval);
        }
        sleep(i);

        return 0;
}
   
Published 38 original articles · won praise 13 · views 4312

Guess you like

Origin blog.csdn.net/YanWenCheng_/article/details/104057108