在为该线程注释pthread_join时多次执行相同的线程子例程

Kun*_*mar 7 c multithreading pthreads

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

    Thread2
    Thread1
    Thread1
Run Code Online (Sandbox Code Playgroud)

我无法理解为什么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);
    }
Run Code Online (Sandbox Code Playgroud)

mk.*_*k.. 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); 
Run Code Online (Sandbox Code Playgroud)

将其替换为

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); 
Run Code Online (Sandbox Code Playgroud)

看看结果是什么。

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

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

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

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

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