Linux pthread_exit()传递线程返回码

(1)通过全局变量进行传递

struct food

{

    int a;

    int b;

    int c;

};

struct food apple;



void* task1(void* arg)

{

    apple.a = 27;

    apple.b = 12;

    apple.c = 39;

    pthread_exit((void*)&apple);

}



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

{

    pthread_t thrd1, thrd2, thrd3;

    void* tret;
pthread_create(&thrd1, NULL, (void*)task1, NULL); pthread_join(thrd1, (void*)&tret);    printf("The food:%d %d %d\n", ((struct food*)(tret))->a, ((struct food*)(tret))->b, ((struct food*)(tret))->c); printf("Main thread exit...\n"); return 0; }

 程序输出:

[root@robot ~]# gcc thread_exit.c -lpthread -o thread_exit

[root@robot ~]# ./thread_exit

The food:27 12 39

Main thread exit...

[root@robot ~]#

(2)通过malloc分配变量进行传递

struct food

{

    int a;

    int b;

    int c;

};



void* task1(void* arg)

{

    struct food *apple = malloc(sizeof(struct food));

    apple->a = 23;

    apple->b = 82;

    apple->c = 59;

    pthread_exit((void*)apple);

}



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

{

    pthread_t thrd1, thrd2, thrd3;

    void* tret;



    pthread_create(&thrd1, NULL, (void*)task1, NULL);

    pthread_join(thrd1, (void*)&tret);



    printf("The food:%d %d %d\n", ((struct food*)(tret))->a, ((struct food*)(tret))->b, ((struct food*)(tret))->c);

    free(((struct food*)tret));

    printf("Main thread exit...\n");



    return 0;

}

 程序输出:

[root@robot ~]# gcc thread_exit.c -lpthread -o thread_exit

[root@robot ~]# ./thread_exit

The food:23 82 59

Main thread exit...

[root@robot ~]#

你可能感兴趣的:(pthread)