Mars
Mars

Reputation: 4995

Reading from a file in different threads in C

I have a multithreaded server program where each thread is required to read the contents of a file to retrieve data requested by the client.

I am using pthreads in C to accomplish creating a thread and passing the function the thread which the thread will execute.

In the function, if I assign to a new FILE pointer with fopen() and subsequently read the contents of the file with fgets(), will each thread have its own file offset? That is, if thread 1 is reading from the file, and it is on line 5 of the file when thread 2 reads for the first time, does thread 2 start reading at line 5 or is it independent of where thread 1 is in the file?

Upvotes: 0

Views: 3114

Answers (1)

abligh
abligh

Reputation: 25199

Each open FILE has only one file pointer. That has one associated FD, and one file position (file offset as you put it).

But you can fopen the file twice (from two different threads or for that matter from the same thread) - as your edit now implies you are doing. That means you'll have two associated FDs and two separate file positions.

IE, this has nothing to do with threads per se, just that if you want separate file positions, you will need two FDs which (with stdio) means two FILEs.

Upvotes: 4

Related Questions