title: Making my matching system thread safe and dealing with concurrency
body: <p>I have a system that I am trying to build that matches users up in real-time.  Based on specific criteria, the user's are matched up 1 to 1. I have the following database tables (kind of like a chat-roulette type system):</p>
  
  <pre><code>Pool
  +UserId
  +Gender
  +City
  +Solo (bool)
  
  Matched
  +UserId
  +PartnerId
  </code></pre>
  
  <p>When a user enters a certain page, they are added to the <code>Pool</code> table with <code>Solo</code> set to true.  The system then searches for another user by querying to the <code>Pool</code> table and returns the results where <code>Solo</code> is true (meaning they do not have a partner) and <code>Gender</code> and <code>City</code> are also equal to whatever they query.  If a match is returned, put both users in the <code>Matched</code> database and turn both of their <code>Solo</code> columns in the <code>Pool</code> table to <code>false</code>.  If they break the connection, they are deleted from the <code>Matched</code> table and their <code>Solo</code> column will change to <code>true</code>.  I am having trouble trying to architect the way this will work with being thread-safe and concurrency. Here are some questions that I got stuck on:</p>
  
  <p>-What if 2 users query the <code>Pool</code> database at the same time and both return the same "solo" user?  How do I prevent this?</p>
  
  <p>-What if 1 user queries the <code>Pool</code> before a user's <code>solo</code> column gets changed, so now that user is returned in the result set, but he is technically not solo</p>
  
  <p>-What other concurrency/thread-safe issues do i face?  Is there a better way than this?</p>