ARTS-S 获取子线程返回值注意事项

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
struct foo {
    int a, b, c, d;
};

void printfoo(const char *s, const struct foo *fp)
{
    printf("%s", s);
    printf("  structure at 0x%lx\n", (unsigned long)fp);
    printf("  foo.a = %d\n", fp->a);
    printf("  foo.b = %d\n", fp->b);
    printf("  foo.c = %d\n", fp->c);
    printf("  foo.d = %d\n", fp->d);
}

void *thr_fn1(void *arg)
{
    struct foo  foo = {1, 2, 3, 4};
    printfoo("thread 1:\n", &foo);
    pthread_exit((void *)&foo);
}

void *thr_fn2(void *arg) {
    printf("thread 2: ID is %lu\n", (unsigned long)pthread_self());
    pthread_exit((void *)0);
}

int main(void) {
    int         err;
    pthread_t   tid1, tid2;
    struct foo  *fp;
    err = pthread_create(&tid1, NULL, thr_fn1, NULL);
    if (err != 0)
        printf("can’t create thread 1:%d", err);
    err = pthread_join(tid1, (void *)&fp);
    if (err != 0)
        printf("can’t join with thread 1:%d", err);
    sleep(1);
    printf("parent starting second thread\n");
    err = pthread_create(&tid2, NULL, thr_fn2, NULL);
    if (err != 0)
        printf("can’t create thread 2:%d", err);
    sleep(1);
    printfoo("parent:\n", fp);
    exit(0);
}
// gcc -Wall main2.c -lpthread -o demo

最后打印的fp的值和第一个线程中初始化的不一样。第一个线程中结构体是个局部变量,函数返回,内存被回收。所以在主线程中就不能访问fp的值。如果想在主线程中获取子线程的值,就要用malloc初始化。

posted on   荷楠仁  阅读(176)  评论(0编辑  收藏  举报

编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义

导航

统计

点击右上角即可分享
微信分享提示