title: Is C read() Thread Safe?
body: <p>I'm writing a program where multiple threads might read from a file simultaneously. No threads are writing to the file, but they might each copy its contents to separate memory segments.</p>
  
  <p>To do implement this, I'm required to use an API that gives me a file descriptor for the file I want to read. I'm reading chunks of the file with C's <a href="http://linux.die.net/man/2/read" rel="nofollow"><code>read</code></a> function. The man page says that, "On success, the number of bytes read is returned (zero indicates end of file), and the file position is advanced by this number." I can't find any definitive information, though, on whether or not the advancement of the file position is thread safe. </p>
  
  <p>Say I have thread T1 and thread T2 reading 1 byte of the file at a time. If <code>read()</code> is thread-safe, I would expect the following:</p>
  
  <pre><code>T1: read() =&gt; file position == 1
  T2: read() =&gt; file position == 1
  T1: read() =&gt; file position == 2
  T2: read() =&gt; file position == 2
  ...
  </code></pre>
  
  <p>But I'm worried that if it's <em>not</em> thread-safe, then the following could happen:</p>
  
  <pre><code>T1: read() =&gt; file position == 1
  T2: read() =&gt; file position == 2
  T1: read() =&gt; file position == 3
  T2: read() =&gt; file position == 4
  ...
  </code></pre>
  
  <p>If it helps, each thread would be using the same file descriptor. In other words, it's the API that opens the file using <code>open()</code>. The threads that are reading the file then fetch that file descriptor based on a client request. If each thread stores its own information about the file position, then it should be fine. I just can't find any information on what holds the file position, and where <code>read()</code> figures out what it is.</p>