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 ~]#
  • 相关阅读:
    机器学习实战
    python中的上下文管理器
    python中的参数传递
    SecureCRT在mac下无法输入中断命令
    Vim练级攻略(转)
    09_MySQL DQL_SQL99标准中的多表查询(外连接)
    08_MySQL DQL_SQL99标准中的多表查询(内连接)
    07_MySQL DQL_多表查询_等值内连接
    06_MySQL DQL_分组查询
    05_MySQL常见函数_分组函数
  • 原文地址:https://www.cnblogs.com/Robotke1/p/3053518.html
Copyright © 2011-2022 走看看