title: How to multithread reading a file in c++11?
body: <p>I have a big file, and i have to read it by chunk. Each time when i read a chunk, i have to do some time consuming operation, so i think multithread reading might help, each thread reads a chunk one by one and does its operation. here is my code in c++11</p>
  
  <pre><code>#include&lt;iostream&gt;
  #include&lt;fstream&gt;
  #include &lt;condition_variable&gt;
  #include &lt;mutex&gt;
  #include &lt;thread&gt;
  using namespace std;
  const int CHAR_PER_FILE = 1e8;
  const int NUM_THREAD = 2;
  int order = -1;
  bool is_reading = false;
  mutex mtx;
  condition_variable file_not_reading;
  void partition(ifstream&amp; is)
  {
      while (is.peek() != EOF)
      {
          unique_lock&lt;mutex&gt; lock(mtx);
          while (is_reading)
              file_not_reading.wait(lock);
  
          is_reading = true;
          char *c = new char[CHAR_PER_FILE];
  
          is.read(c, CHAR_PER_FILE);
          order++;
  
          is_reading = false;
  
          file_not_reading.notify_all();
          lock.unlock();
  
          char oc[3];
          sprintf(oc, "%d", order);
          this_thread::sleep_for(chrono::milliseconds(2000));//some operations that take long time
          ofstream os(oc, ios::binary);
          os.write(c, CHAR_PER_FILE);
          delete[] c;
          os.close();
      }
  }
  
  int main()
  {
      ifstream is("bigfile.txt",ios::binary);
      thread threads[NUM_THREAD];
      for (int i = 0; i &lt; NUM_THREAD; i++)
          threads[i] = thread(partition, ref(is));
  
      for (int i = 0; i &lt; NUM_THREAD; i++)
          threads[i].join();
  
      is.close();
      system("pause");
      return 0;
  }
  </code></pre>
  
  <p>But my code didn't work, it only created 4 files instead of `bigfilesize/CHAR_PER_FILE, and threads seem got stuck, how can i make it work?</p>
  
  <p>Is there any c++11 multithread reading file implementation or example?</p>
  
  <p>Thanks.</p>