title: Asynchronous Server, Handle Disconnections while waiting for callbacks
body: <p>i have one question according to asynchronous server management. I am using <strong>libevent2</strong> and (for my own learning experience) plain ANSI C.
  I do my stresstests with ab from the apache2 utils. Mostly <code>-n 10000</code> and <code>-c 400</code>. 
  My database is a sql server on a debian computer in my local network. So the connection is pretty fast.
  I profile my app also with valgrind (<code>--leak-check=full --show-reachable=yes</code>)</p>
  
  <p>I have one issue now.
  When I do synchronous calls to the sql database than everything works fine. But it is all done on the main thread, so it takes some time for new clients to receive data (while the stress is running). 
  When I do asynchronous calls to the sql database than everything works fine as well, as long as no client disconnects BEFORE the sql call returns. As soon as the sql call returns and the client is disconnected already, i get a lot of invalid read erros (of course) because its buffer is freed already, the socket is closed etc. I tried a lot of different things already but couldn't get a proper solution.</p>
  
  <p>I just wanted to ask in general how you handle stuff like this? Do you keep a BST for example, which includes all the clients connected and when an async call returns you search for it in it? If it is still in there u execute the callback otherwise discard it? I think this could kill performance quite a bit.
  I also tried to check if the socket is still open, but it was kinda weird. 
  <code>recv(fd, buffer, 1, MSG_PEEK)</code> always <code>returned -1</code> (on opened and closed non-blocking sockets).. </p>
  
  <p>Well, it is kinda hard to explain what i did already so i just wait for what you guys will answer :-)</p>
  
  <p>Greetings
  Markus</p>
  
  <p>update:
  i just had the crazy idea to use a mutex for each connection. When i enter the async call i lock it, and release it after it returns.. :-) but i dont trust this method.. it doesnt sound right.. can anyone recommend that approach? </p>
  
  <p>update 2: I tried my idea and it works great. It was a bit tricky to get it right but the locking did it</p>