7

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

    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);
    }
4

2 回答 2

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

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

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

于 2012-04-26T02:31:13.610 回答
1

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

setvbuf(stdout, NULL, _IONBF, 0);

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

于 2012-04-26T02:05:04.990 回答