在打印之前调用线程但打印在线程之前执行

Call threads before print yet print executes before threads

自从我从 OS class 玩 pthreads 以来已经有一年左右的时间了,我一直试图重新投入其中只是为了好玩。下面是我从 运行 到 online source 的简单线程练习的代码。我担心的是教程说输出应该是:

Thread 1
Thread 2
pthread_create() for thread 1 returns: 0
pthread_create() for thread 2 returns: 0

这对我来说很有意义。但是我得到

pthread_create() for thread 1 returns: 0
pthread_create() for thread 2 returns: 0
Thread 1
Thread 2

pthread1.c

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

void *print_message_function( void *ptr );

main()
{
     pthread_t thread1, thread2;
     const char *message1 = "Thread 1";
     const char *message2 = "Thread 2";
     int  iret1, iret2;

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

     if(iret1)
     {
         fprintf(stderr,"Error - pthread_create() return code: %d\n",iret1);
         exit(EXIT_FAILURE);
     }

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

     if(iret2)
     {
         fprintf(stderr,"Error - pthread_create() return code: %d\n",iret2);
         exit(EXIT_FAILURE);
     }

     printf("pthread_create() for thread 1 returns: %d\n",iret1);
     printf("pthread_create() for thread 2 returns: %d\n",iret2);


     pthread_join( thread1, NULL);
     pthread_join( thread2, NULL);

     exit(EXIT_SUCCESS);

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

这就是所谓的竞争条件。

有可能,在线程 1 创建后,调度程序首先调度线程 1 函数 1,然后线程函数可能首先执行,然后您的 main() 打印出来。

当我 运行 你的程序时在我的系统上。

jeegar@jeegarp:~$ ./a.out 
pthread_create() for thread 1 returns: 0
pthread_create() for thread 2 returns: 0
Thread 2 
Thread 1 
jeegar@jeegarp:~$ ./a.out 
pthread_create() for thread 1 returns: 0
pthread_create() for thread 2 returns: 0
Thread 1 
Thread 2 

仔细看看教程。在我看来有一个错误:代码和它的结果不匹配(代码是关于 return 来自 pthread_create 的代码,打印出来的是关于线程 return 代码,这是不可访问的,因为对 pthread_join 的调用是使用 NULL 作为第二个参数以及 print_message_function 缺少 return 任何合理的东西)

if(iret2) 之前尝试 sleep(0); 以获得乐趣...

执行顺序取决于OS调度algorithm.Hence,线程或创建线程的函数中的任何一个都可以被调度(取决于OS调度算法)。