Pthread ID不显示,代码生成错误的输出

时间:2018-12-03 02:57:46

标签: pthreads

问题陈述

在Linux上编码和编译并运行C程序

创建三个线程的程序

线程1

线程2

线程3。

并行运行这些线程

每个线程将显示其进程和线程ID。

*线程将具有其他功能

输出\

线程1将显示一个字符串。

线程2将显示一个字符串

线程3将显示一个字符串

所有信息都将作为参数传递给线程函数以进行显示

父/主线程处于等待状态,直到其他线程结束执行。

最终,所有线程将终止。

注意

代码在终端中使用以下命令编译

gcc Bring.c -lpthread

以下是结果

线程1的pthread_create()返回:0

线程2的pthread_create()返回:0

线程3的pthread_create()返回:0

XD-130201818部件ID

Bin 21第三行

向南存储61

输出不足

#include <stdio.h>

#include <stdlib.h>

#include <pthread.h>

void*print_message_function(void*ptr);

main()

  {

  pthread_t thread1,thread2;thread3;

  const char*message1="XD-130201818 Part ID";

  const char *message2 = "Bin 21 3rd row ";

  const char *message3 = "Store 61 south ";

  int  iret1, iret2,iret3;

  /* Create independent threads each of which will execute 
       function */

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

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

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

   iret3 = pthread_create( &thread1, NULL, print_message_function, (void*) 
   message3);

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

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

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

  printf("pthread_create() for thread 3 returns: %d\n",iret3);

  /* Wait till threads are complete before main continues. Unless we  */

  /* wait we run the risk of executing an exit which will terminate   */

  /* the process and all threads before the threads have completed.   */


  pthread_join( thread1, NULL);

  pthread_join( thread2, NULL); 

  pthread_join( thread3, NULL);

 exit(EXIT_SUCCESS);

 }

 void *print_message_function( void *ptr )

{
 char *message;

 message = (char *) ptr;

 printf("%s \n", message);
}

0 个答案:

没有答案