【问题标题】:Unexpected output in pthreadpthread 中的意外输出
【发布时间】:2012-06-02 06:49:56
【问题描述】:

您好,线程中的上述代码显示 0 (tid = 0) 而不是 8...可能是什么原因?在 PrintHello 函数中,我正在打印 threadid,但我正在发送值 8,但它正在打印 0 作为输出

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>


void *PrintHello(void *threadid)
{
   int *tid;
   tid = threadid;
   printf("Hello World! It's me, thread #%d!\n", *tid);
   pthread_exit(NULL);
}

int main(int argc, char *argv[])
{
   pthread_t thread1,thread2;
   int rc;
   int value = 8;
   int *t;
   t = &value;

   printf("In main: creating thread 1");
    rc = pthread_create(&thread1, NULL, PrintHello, (void *)t);
     if (rc)
    {
        printf("ERROR; return code from pthread_create() is %d\n", rc);
        exit(-1);
        }


   printf("In main: creating thread 2\n");
    rc = pthread_create(&thread1, NULL, PrintHello, (void *)t);
     if (rc)
    {
        printf("ERROR; return code from pthread_create() is %d\n", rc);
        exit(-1);
        }


   /* Last thing that main() should do */
   pthread_exit(NULL);
}

【问题讨论】:

    标签: c posix


    【解决方案1】:

    拥有8 的实际对象是value,它是main 函数的本地对象,因此在main 退出后访问是无效的。

    在子线程尝试访问此局部变量之前,您无需等待它们完成,因此行为未定义。

    一种解决方法是让您的main 在使用pthread_join 退出之前等待它的子线程。

    (我假设您在第二次调用 pthread_create 时打错了字,并打算传递 thread2 而不是 thread1。)

    例如

    /* in main, before exiting */
    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);
    

    【讨论】:

    • 另外,传递参数时不应该是&amp;t吗?
    • 我的意思是传递给pthread_create的第四个参数?我没用过 pthreads 所以不太确定。
    • 哎呀..对不起..我在valuet 之间感到困惑。没有看到 t 被定义为 int*
    • @Charles Bailey:感谢您的修复:) 我还没有测试过,一旦我今天去工作场所,我会测试它:).. 实际上我想要做的是,thread1 是读取一个值,该值由thread2处理并给出输出。那么无论如何要在线程之间传递值吗?我可以使用共享内存吗?或者在 main() 文件中声明一个全局变量?谢谢
    • @Charles Bailey:实际上我已经在 beaglebone (ARM) 中测试了这段代码,当我在笔记本电脑中使用 (x86) ubuntu 12.04 测试相同的代码时,它给出了 0 作为输出,它给出了输出作为 8 本身。我没有添加 pthread_join 也仍然给出 8 作为输出。有什么原因吗?可能是版本问题?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-24
    • 1970-01-01
    • 1970-01-01
    • 2021-10-13
    • 2020-02-21
    相关资源
    最近更新 更多