The problem is: second write which is issued internally by boost cannot be protected by the same mutex which is used for protected access to the socket in my code.
So, the question is: how can I safely close the socket?
You should use strands: http://www.boost.org/doc/libs/1_53_0/doc/html/boost_asio/overview/core/stran...
What do you mean by "use strands". I'm using strands for my completion handlers. Also I can use strand to commit async operations and to post close(). But that fact doesn't help given that the second buffer write (from my scenario) is not initiated from within the same strand. It seems that some internal boost strand is used to commit second and later buffer writes when using scatter-gather async_write API. So the question "how to safely close socket?" still remains.
All the internal/intermediate completion handlers of the composed operation async_write would use the same strand, as stated in the docs (see the link in my previous comment): "In the case of composed asynchronous operations, such as async_read() or async_read_until(), if a completion handler goes through a strand, then all intermediate handlers should also go through the same strand. This is needed to ensure thread safe access for any objects that are shared between the caller and the composed operation (in the case of async_read() it's the socket, which the caller can close() to cancel the operation)." So if you post close() to *this* strand - it won't cause race-condition with the composed operation in your scenario, will it?