title: Threads sharing resources C++
body: <p>I currently have two threads running in my program:</p>
  
  <ol>
  <li><p>Main thread - Grabs image from a webcam, stored in a <a href="http://www.edwardrosten.com/cvd/cvd/html/classCVD_1_1Image.html!" rel="nofollow">CVD</a> image. Does processing on this image.</p></li>
  <li><p>Server thread - sends the full image data stored in the above CVD image to its clients using named pipes. </p></li>
  </ol>
  
  <p>When I run my program it works for a very short while before crashing with the following exception:</p>
  
  <pre><code>0xC000005: Access violation reading location 0x0000000
  </code></pre>
  
  <p>Which I assume is because my server thread is attempting to access the image at the same time as the main thread.</p>
  
  <p>I haven't done any concurrent programming before (this is my first time) but I have a vague idea about how to solve it at the moment.</p>
  
  <p>My plan is to have some sort of lock that prevents access to the image from the main thread when the server is preparing to send it to the client. However I realised there might be a problem where the server thread constantly keeps the resource as the client is constantly requesting a new frame. So I am thinking to only respond to the client whenever a new frame is grabbed from the webcam to avoid the blocking issue above.</p>
  
  <p>To sum this up:</p>
  
  <p>Main thread:</p>
  
  <pre><code>1. If Image is available
     then - Lock image, copy over new data from webcam, release image
     else - goto 1
  2. Do processing
  </code></pre>
  
  <p>Server:</p>
  
  <pre><code>1. Receive request for new frame from client
  2. If (haven't sent the current frame yet)
     then - Lock CVD image access, send over frame, release image.
     else - wait until new image available.
  3. goto 1
  </code></pre>
  
  <p>My question is, would this be a suitable solution? and what do I need in order to implement this? i.e. how do I stop execution of certain parts of my code whilst another thread is executing a part of its own code.</p>
  
  <p>Some more info:</p>
  
  <ol>
  <li>I am using VS2010 C++ </li>
  <li>The client is in C# and there is only 1 client.</li>
  <li>I am accessing the image data from the CVD image using image[x][y] which returns a byte value representing the intensity of the image.</li>
  <li>There is a copyTo() function available with the CVD image. It seems to do a memory copy of the image to create a new object with the same data. Would this be useful?</li>
  <li>I cannot run the program in debug mode because I am working off an existing codebase with no debug mode set.</li>
  </ol>