title: Using semaphore for multithreading in C
body: <p>The Idea here is to create a file to be written to.  I'm trying to create ten threads and have them print to the file 10 times each. Using a semaphore to stop multiple threads from writing to the file at once.  Everything compiles and I don't get an error exit, however I can't understand why running the program numerous times: 1)It doesn't print 100 lines to the file, infact it's far less 2) The number of lines printed to the file vary each time.</p>
  
  <pre><code>    #include &lt;stdio.h&gt;
      #include &lt;sys/types.h&gt;
      #include &lt;stdlib.h&gt;
      #include &lt;unistd.h&gt;
      #include &lt;pthread.h&gt;
      #include &lt;semaphore.h&gt;
  
      #define READ    "r"
      #define NEW     "w"
      #define ADD     "a"
      #define NL      "\n"
      #define TAB     "\t"
  
      #define FNAME   "PROCTAB.txt"
      #define MAX_STRING_LEN  80
      #define NUMBER_OF_THREADS       10
      FILE *fp;
      sem_t mutex;
      int counter;
  
      FILE *makeTextFile(char *fname, char mode){
         FILE *localFP;
         localFP = fopen(fname, &amp;mode);
         return (localFP);
  }
  
      void *print_message(void *tid){
          int i;
          for (i = 0; i &lt; 10; i++){
              sem_wait(&amp;mutex);
              fp = fopen(FNAME, ADD);
              fprintf(fp, "Thread %d is running.\n", tid);
              fclose(fp);
          sem_post(&amp;mutex);
       }
      }
  
      int threads(){
       const char *fName = "PROCTAB.txt";
           int status;
           pthread_t threads[NUMBER_OF_THREADS];
        fp = makeTextFile(FNAME, 'w');
           fprintf(fp, "Process ID: %ld\n", (long)getpid());
           fclose(fp);
       int i;
           for (i =0; i &lt; NUMBER_OF_THREADS; i++){
              status = pthread_create(&amp;threads[i], NULL, &amp;print_message, (void *)i);
              if (status != 0){
                  printf("pthread_create returned error code %d\n", status);
                  exit(-1);
                   }
              }
        return 0;
     }
  </code></pre>
  
  <p>My main function is contained in a separate file. </p>