title: C - Reading from a file with threads
body: <p>I have to read from a file some numbers with 5 threads (every thread reads one number), synchronizing the access to the file itself. I wanted to know if the sequent ways to proceed so that threads share the mutex and the file pointer are equivalent:</p>
  
  <p>1) declare mutex and file to read as global variables</p>
  
  <pre><code>#include &lt;....&gt;
  
  pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
  FILE *fp;
  
  int main(int argc,char *argv[]){
  
      fp=open_file(argv[1]);
  }
  </code></pre>
  
  <p>and 2) define a data structure for the threads and then associate its field with the mutex and the file in the main function</p>
  
  <pre><code>#include &lt;....&gt;
  
  struct data
  {
     pthread_t tid;
     pthread_mutex_t *ptmx;
     FILE *f;
  
    .....
  }
  
  int main(int argc,char* argv[])
  {
     FILE *fp=open_file(argv[1]);
     struct data td[5];
     pthread_mutex_t mtx;
  
     pthread_mutex_init(&amp;mtx,NULL)
  
     for(i=0;i&lt;5;i++)
     {
        td[i].f=fp;
        td[i].ptmx=&amp;mtx;
     }
  
     ....
  }
  </code></pre>
  
  <p>i've reported only a piece of the code for simplicity, and supposed that the file is passed with line command.</p>