• 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 ~]#
  • 相关阅读:
    [转]HDR渲染器的实现(基于OpenGL)
    32位微机的内存管理模式
    王爽汇编检测点1.1
    标志位的说明
    通用寄存器的作用
    Debug初次使用
    昨天纠结了一天要始学习dos汇编还是win32汇编,终于想通了
    CPU对存储器的读写(二、数据总线、控制总线)
    CPU对存储器的读写(一、地址总线)
    段寄存器的引用
  • 原文地址:https://www.cnblogs.com/Robotke1/p/3053518.html
Copyright © 2020-2023  润新知