Subject: Re: [boost] [asio] ip::tcp::socket thread safety
From: Brad Higgins (bhiggins_at_[hidden])
Date: 2012-04-02 12:21:51
On Apr 2, 2012, at 11:07 AM, Gaetano Mendola wrote:
> Hi all,
> reading the manual I see that ip::tcp::socket thread safety on shared object is not safe.
> In my application I'm using:
> boost::asio::async_read( ip::tcp::socket , ...)
> the application queue an async_read or an async_connect inside
> the receiving handler (in case of error it retry the connection).
>> From an external thread (to stop the reception) I perform a:
> do I have realy to synchronize the async_connect/async_read with
> shutdown/close ?
> Using a mutex to protect those calls seems an overkill, may be shutdown
> and close can be called in concurrency with async_connect/async_read and the
> documentation is just conservative?
I would stick to what the documentation says.
The io_service is thread-safe, so to synchronize the socket operations from different threads, you can use io_service::post() from your "external thread". Implement a function that performs the shutdown() and close() calls, and post that function as a completion handler with io_service.post(), using the io_service instance that is handling your async_connect() and async_read() calls. That way, all of the thread-unsafe ip::tcp::socket calls will occur in the single thread that is running io_service.run(), guaranteeing thread safety.
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk