C中的多线程程序不提供两个线程的输出

时间:2015-01-30 23:35:54

标签: c linux multithreading

我在C中有这个程序:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define OUTPUTNAME "write.out"
#define OUTPUTNAME1 "fprint.out"

void *syscall_writer_function();
void *stdlibrary_writer_function();
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
int  counter = 0;

main()
{

   int rc1, rc2;
   pthread_t thread1, thread2;

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

   if( (rc1=pthread_create( &thread1, NULL, &stdlibrary_writer_function, NULL)) )

   {

      printf("Thread creation failed: %d\n", rc1);

   }

   if( (rc2=pthread_create( &thread2, NULL, &syscall_writer_function, NULL)) )
   {

      printf("Thread creation failed: %d\n", rc2);
   }

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

   exit(EXIT_SUCCESS);
}

void *syscall_writer_function()
{

   long i;
   int fd;
   if ((fd=open(OUTPUTNAME,O_WRONLY|O_CREAT,0644)) < 0){
      fprintf(stderr,"Can't open %s. Bye.\n",OUTPUTNAME);
      exit(1);
   }
   for (i=0; i<50000; i++) { /* write 50,000 Ys with write */
      if (write(fd,"Y",1) < 1) {
         fprintf(stderr,"Can't write. Bye\n");
         exit(1);
      }
      }

   pthread_mutex_lock( &mutex1 );
   counter++;
   printf("Syscall finished\n");
   printf("Counter value: %d\n",counter);
   close(fd);
   exit(0);

  pthread_mutex_unlock( &mutex1 );
}

void *stdlibrary_writer_function()
{

   long i;
   FILE *fp;
   if ((fp=fopen(OUTPUTNAME1,"w")) == NULL) {
      fprintf(stderr,"Can't open %s. Bye.\n",OUTPUTNAME1);
      exit(1);
   }
   for (i=0; i<400000; i++) { /* write 400,000 Xs with fprintf */
      if (fprintf(fp,"X") < 1) {
      fprintf(stderr,"Can't write. Bye\n");
      exit(1);
      }
   }

   pthread_mutex_lock( &mutex2 );
   counter++;
   printf("Stdlibrary finished\n");
   printf("Counter value: %d\n",counter);
   fclose(fp);
   exit(0);
   pthread_mutex_unlock( &mutex2 );

}

它应该给出两个线程的输出,如:

Syscall finished
Counter value: 1
Stdlibrary finished
Counter value: 2

,反之亦然,stdlibrary first和syscall second。

但是,它只提供如下输出:

Syscall finished
Counter value: 1

为什么会这样?有什么问题?

0 个答案:

没有答案