title: How to close a SOCKET when using IOCP?
body: <p>I have a server application that uses IOCP. I want to know what is the proper way to close a <code>SOCKET</code>.</p>
  
  <p>If I simply call <code>closesocket()</code> (for a <code>SOCKET</code> with a handle of for example <code>12345</code>), and this <code>SOCKET</code> has pending IO operations (for example: a pending <code>WSARecv()</code> request), then the following scenario could happen:</p>
  
  <ul>
  <li><p>I call <code>closesocket()</code> which will destroy the <code>SOCKET</code>.</p></li>
  <li><p>I accept another <code>SOCKET</code> with the same handle of <code>12345</code>.</p></li>
  <li><p>I deque the pending <code>WSARecv()</code> completion packet for the <code>SOCKET</code> with the handle of <code>12345</code>. Now I would assume that this completion packet is for the current <code>SOCKET</code> with the handle of <code>12345</code>, but in fact it is for the <code>SOCKET</code> that was previously closed (this is he main problem with this approach).</p></li>
  </ul>
  
  <p>So this is obviously a bad approach.</p>
  
  <p>The second approach that seems correct is the following:</p>
  
  <ul>
  <li><p>I associate a <code>struct</code> instance with each <code>SOCKET</code>. The <code>struct</code> has the following members: an <code>int</code> called <code>number_of_pending_IO_operations</code>, and a <code>boolean</code> called <code>Is_SOCKET_being_closed</code>.</p></li>
  <li><p>When I issue an IO operation for the <code>SOCKET</code> (for example: a <code>WSASend()</code> request), I increment <code>number_of_pending_IO_operations</code> by <code>1</code>, and when I deque a completion packet for the SOCKET, I decrement <code>number_of_pending_IO_operations</code> by <code>1</code>.</p></li>
  <li><p>Now, when I want to close the <code>SOCKET</code>, I don't simply call <code>closesocket()</code>, but rather I call <code>CancelIOEx()</code> to cancel all pending IO operations for the <code>SOCKET</code>, and I also set <code>Is_SOCKET_being_closed</code> to <code>true</code>.</p></li>
  <li><p>When I am about to issue another IO operation (for example: a <code>WSASend()</code> request), I would check the value of <code>Is_SOCKET_being_closed</code>, and if it is <code>true</code>, I would not issue the IO operation.</p></li>
  <li><p>Now I simply wait for all of the completion packets to be dequeued, and when <code>number_of_pending_IO_operations</code> reaches <code>0</code> and <code>Is_SOCKET_being_closed</code> is set to <code>true</code>, I call <code>closesocket()</code>.</p></li>
  </ul>
  
  <p><em>Of course I would have race conditions, so I would use critical sections.</em></p>
  
  <p>Is the second approach a correct way to close a <code>SOCKET</code>, or is there a better way?</p>