zoukankan      html  css  js  c++  java
  • 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 ~]#
  • 相关阅读:
    YL杯超级篮球赛 (Standard IO)
    Window (Standard IO)
    toj1026 Network 双连通分量
    poj3177 Redundant Paths 双连通分量
    poj1144 Network 双连通分量
    bzoj1269
    bzoj1800
    CF911D
    CF910C
    CF910B
  • 原文地址:https://www.cnblogs.com/Robotke1/p/3053518.html
Copyright © 2011-2022 走看看