【问题标题】:Multiple execution of same thread subroutine on commenting pthread_join for that thread [duplicate]在为该线程注释 pthread_join 时多次执行同一线程子例程[重复]
【发布时间】:2012-04-25 19:06:50
【问题描述】:

我是线程新手。 在这里,如果我评论 pthread_join(thread1, NULL) 那么在输出中有时我会得到 ​​p>

    Thread2
    Thread1
    Thread1

我无法理解为什么 Thread1 跟踪会出现两次以及 pthread_join 的确切功能是什么。

另外,请参考一些针对初学者的线程概念教程。

    void *print_message_function( void *ptr );
    main()
    {
            pthread_t thread1, thread2;
            char *message1 = "Thread 1";
            char *message2 = "Thread 2";
            int  iret1, iret2;
            iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1);
            iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2);
            pthread_join( thread1, NULL);

            pthread_join( thread2, NULL); 

            printf("Thread 1 returns: %d\n",iret1);
            printf("Thread 2 returns: %d\n",iret2);
            exit(0);
    }

    void *print_message_function( void *ptr )
    {
            char *message;
            message = (char *) ptr;
            printf("%s \n", message);
    }

【问题讨论】:

  • 只是为了确认我可以使用 gcc 4.4.6 在 CentOS 6.2 上重现这个。好拼图! (+1)
  • 如果您使用-pthread 选项而不是使用-lpthread 进行构建,会有什么不同吗?我想知道神秘的-D_REENTRANT 选项是否会影响printf() 呼叫的处理方式。我不这么认为,但你永远不知道......
  • 线程 1 的两次打印之间是否有换行符?因为在我的系统上它们打印在同一行。
  • @Gabriel:关于通过堆栈共享数据 - 我不确定我明白你指的是什么。传递给线程的数据是指向字符串文字的指针,它们是静态分配的,因此与main() 的生命周期(除了整个进程的生命周期)没有任何关系。
  • 线程函数不返回任何内容。在某些情况下,非 void 函数中缺少返回值可能会导致奇怪的行为。您是否尝试将return SomeValue; 添加到print_message_function()

标签: c multithreading pthreads


【解决方案1】:

如果我得到这些结果,首先我会做以下事情:

1) 而不是下面的行,

iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1);

iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2);
pthread_join( thread1, NULL);

pthread_join( thread2, NULL); 

替换为,

iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1);

pthread_join( thread1, NULL);
iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2);

pthread_join( thread2, NULL); 

看看结果如何。

2) 在你的线程函数中,你需要调用 pthread_exit("Exit");这是退出线程函数的正确方法。在函数结束时执行。

void *print_message_function( void *ptr )
{
        char *message;
        message = (char *) ptr;
        printf("%s \n", message);
        pthread_exit("Exit"); 
    }

如果您这样做,理想情况下您应该不会遇到任何问题。在每种情况下,我都假设您正在使用 gcc -D_REENTRANT -o threadex threadex.c -lpthread 编译程序

这不是最终的解决方案。如果一切顺利,那么我们可以进行下一步,一次启动两个线程。

请在合并这些更改后分享反馈。

【讨论】:

    【解决方案2】:

    也许输出缓冲区没有正确刷新。在进行多线程处理并将输出传送到文件时,我遇到了一个非常相似的问题——有时输出会出现两次。尝试将此行添加到您的主要功能:

    setvbuf(stdout, NULL, _IONBF, 0);
    

    这将强制在每次写入时刷新输出缓冲区。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-13
      • 1970-01-01
      • 1970-01-01
      • 2014-03-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多