title: send and recv on same socket from different threads not working
body: <p>I read that it should be safe from different threads concurrently, but my program has some weird behaviour and I don't know what's wrong.</p>
  
  <p>I have concurrent threads communicating with a client socket</p>
  
  <ol>
  <li>one doing send to a socket</li>
  <li>one doing select and then recv from the same socket</li>
  </ol>
  
  <p>As I'm still sending, the client has already received the data and closed the socket.
  At the same time, I'm doing a select and recv on that socket, which returns 0 (since it is closed) so I close this socket. However, the send has not returned yet...and since I call close on this socket the send call fails with EBADF.</p>
  
  <p>I know the client has received the data correctly since I output it after I close the socket and it is right. However, on my end, my send call is still returning an error (EBADF), so I want to fix it so it doesn't fail.</p>
  
  <p>This doesn't always happen. It happens maybe 40% of the time. I don't use sleep anywhere. Am I supposed to have pauses between sends or recvs or anything?</p>
  
  <p>Here's some code:</p>
  
  <p>Sending:</p>
  
  <pre><code>while(true)
  {
      // keep sending until send returns 0
      n = send(_sfd, bytesPtr, sentSize, 0);
  
      if (n == 0)
      {
          break;
      }
      else if(n&lt;0)
      {
          cerr &lt;&lt; "ERROR: send returned an error "&lt;&lt;errno&lt;&lt; endl; // this case is triggered
          return n;
      }
  
      sentSize -= n;
      bytesPtr += n;
  }
  </code></pre>
  
  <p>Receiving:</p>
  
  <pre><code> while(true)
  {
      memset(bufferPointer,0,sizeLeft);
      n = recv(_sfd,bufferPointer,sizeLeft, 0);
      if (debug) cerr &lt;&lt; "Receiving..."&lt;&lt;sizeLeft&lt;&lt;endl;
      if(n == 0)
      {
          cerr &lt;&lt; "Connection closed"&lt;&lt;endl; // this case is triggered
          return n;
      }
      else if (n &lt; 0)
      {
          cerr &lt;&lt; "ERROR reading from socket"&lt;&lt;endl;
          return n;
      }
       bufferPointer += n;
       sizeLeft -= n;
       if(sizeLeft &lt;= 0) break;
  
  }
  </code></pre>
  
  <p>On the client, I use the same receive code, then I call close() on the socket.
  Then on my side, I get 0 from the receive call and also call close() on the socket
  Then my send fails. It still hasn't finished?! But my client already got the data!</p>