Distributions
Ubuntu
Fedora
CentOS
中文资源站
网易开源镜像站
zhongshaohua
V2EX  ›  Linux

创建线程时,为什么线程函数中没有输出参数值?

  •  
  •   zhongshaohua · Jun 13, 2016 · 3339 views
    This topic created in 3636 days ago, the information mentioned may be changed or developed.
    struct thread_args {
    int data;
    };

    static void *thread_func(void *arg){
    struct thread_args *t_args = (struct thread_args *)arg;
    printf("%d\n", t_args->data);
    }

    int create_thread(void){
    int ret;
    pthread_t tid;
    struct thread_args args;

    args.data = 1;
    ret = pthread_create(&tid, NULL, thread_func, &args);
    if (ret != 0) {
    printf("Call pthread_create failed, ret %d\n", ret);
    return -1;
    }

    return 0;
    }
    8 replies    2016-06-14 15:38:15 +08:00
    hyq
        1
    hyq  
       Jun 13, 2016
    struct thread_args args;
    不要传局部变量过去, malloc 一个出来
    zhongshaohua
        2
    zhongshaohua  
    OP
       Jun 13, 2016
    @hyq 即时是局部变量,也应该有一个副本值啊,应该能输出啊
    jiangtao92
        3
    jiangtao92  
       Jun 13, 2016   ❤️ 1
    会不会是因为没有 join ?
    hyq
        4
    hyq  
       Jun 13, 2016
    @jiangtao92 如果是完全没有输出,那应该就是没有 join 的原因,主线程退出了,进程就结束了
    ryd994
        5
    ryd994  
       Jun 13, 2016 via Android
    可以用局部,但是你要保证这个局部在线程执行完之前是有效的,也就是说你要在作用域内 join 。再过分一点,如果你用锁之类的机制保证只在作用域内使用该内存的话,也可以。
    你现在的问题是没有 join ,主线程退出时吧子线程干掉了
    zhongshaohua
        6
    zhongshaohua  
    OP
       Jun 14, 2016
    @hyq 谢谢
    zhongshaohua
        7
    zhongshaohua  
    OP
       Jun 14, 2016
    @ryd994 正解 谢谢老司机
    zhongshaohua
        8
    zhongshaohua  
    OP
       Jun 14, 2016
    @jiangtao92 确实是因为没有 join 谢谢
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1332 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 23:51 · PVG 07:51 · LAX 16:51 · JFK 19:51
    ♥ Do have faith in what you're doing.