title: C++ Opencv: Performance in multithreaded environment
body: <p>In my C++ program I create 3 pthread. The first 2 threads create socket and receive data (integers) from different ports. The main() function at the same time is writing these received values (by the 2 threads) into a text file. I have a third thread which starts to capture images from a camera using opencv libraries and I want to save each frame as a png file. I know my camera can go up to maximum 60FPS which brings us to sampling rate of 16 milliseconds. I use the function <code>gettimeofday()</code> before and after capturing the image to obtain the timing of image acquisition.</p>
  
  <pre><code>//Thread number 3
  Mat IMG; 
  unsigned long ms;
  VideoCapture cap(0);
  struct timeval tp1,tp2;
  while(1)
  {
     gettimeofday(&amp;tp1,NULL);
     cap&gt;&gt;IMG;
     gettimeofday(&amp;tp2,NULL);
     ms=10000000*(tp1.tv_sec-tp2.tv_sec)+(tp1.tv_usec-tp2.tv_usec);
     cout&lt;&lt;ms/1000&lt;&lt;endl;
  }
  </code></pre>
  
  <p>My main program starts writing to the text file once the data is available by the other 2 threads which happens roughly 10 seconds after the first image is captured. During this 10 seconds by monitoring the time, each frame takes no longer than 16 ms to be captured. However as soon as the text file writing is initialized, even if I dont save the images, the timing that I get is not always 16ms and sometimes goes up to 35 milliseconds (although most of the time this duration is still 16ms or less). Now in addition if I start saving the images this time increases. I tried to put the <code>imwrite()</code> funtion for image saving into another thread but it didnt help. How can I avoid this? is memory access so privileged that even writing into a text file can slow down other threads that are only responsible to capture images?  Is there any way to preserve this timing and save the images while running other threads and the main function doing his own job? </p>