【问题标题】:Call threads before print yet print executes before threads在打印之前调用线程但打印在线程之前执行
【发布时间】:2016-11-08 06:14:15
【问题描述】:

自从我在操作系统课上与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);
}

【问题讨论】:

  • 看来你的教程是错误的。消息可以按任意顺序出现,甚至可以穿插出现。
  • 新线程可能(但并非总是)在 pthread_create() 返回之前开始运行。因此,您可以在每个线程启动之前或之后在 main() 中重新获得控制权。这种不可预测性意味着显示语句可能以与教科书答案不同的顺序出现。
  • 贴出的代码编译不干净!编译时,始终启用所有警告,然后修复这些警告。 (对于gcc,至少使用:-Wall -Wextra -pedantic 我也使用:-Wconversion -std=gnu99)1)main() 函数只有两个有效签名:int main( void )int main( int argc, char *argv[] ) 请注意,两者都有返回类型int 2) main() 函数缺少最后的右大括号 '}',3) 函数:print_message_function() 的返回类型为 void*,但缺少实际的 return 语句。
  • 执行多线程程序时,不保证执行哪个线程,按什么顺序执行。
  • 函数:print_message_function() 应该通过:pthread_exit( NULL );退出

标签: c linux pthreads posix


【解决方案1】:

这就是所谓的竞争条件。

有可能,在创建线程 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 

【讨论】:

    【解决方案2】:

    仔细查看教程。在我看来有一个错误:代码及其结果不匹配(代码是关于 pthread_create 的返回代码,打印输出是关于线程返回代码,因为调用 pthread_join 使用 NULL 作为第二个参数以及 print_message_function 没有返回任何合理的值)

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

    【讨论】:

      【解决方案3】:

      执行顺序取决于操作系统调度算法。因此,线程或创建线程的函数中的任何一个都可以被调度(取决于操作系统调度算法)。

      【讨论】:

        猜你喜欢
        • 2020-11-10
        • 2017-01-10
        • 2013-06-12
        • 1970-01-01
        • 1970-01-01
        • 2011-06-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多