SegFault
SegFault

Reputation: 2220

C - Reading from a file with threads

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:

1) declare mutex and file to read as global variables

#include <....>

pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
FILE *fp;

int main(int argc,char *argv[]){

    fp=open_file(argv[1]);
}

and 2) define a data structure for the threads and then associate its field with the mutex and the file in the main function

#include <....>

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(&mtx,NULL)

   for(i=0;i<5;i++)
   {
      td[i].f=fp;
      td[i].ptmx=&mtx;
   }

   ....
}

i've reported only a piece of the code for simplicity, and supposed that the file is passed with line command.

Upvotes: 1

Views: 2612

Answers (1)

Hasturkun
Hasturkun

Reputation: 36422

Yes, these are completely equivalent.

In both cases, the threads have the mutex and FILE pointer visible, sharing the same values.

Upvotes: 2

Related Questions