2

From the documentation, most Asio classes are NOT thread-safe. So I wonder is it safe for a user thread to access an object in async operation?

For example, if a socket is async connecting:

asio::async_connect(socket, endpoint_iterator, handler);

I suppose there will be an Asio internal thread (e.g. one runs io_service.run()) to do something on socket (No?). Is it safe to call socket.close() before the async_connect finishes (for timeout for example)? Will it race with any Asio internal thread?

updogliu
  • 6,066
  • 7
  • 37
  • 50
  • possible duplicate of [Is ip::tcp::socket.close() thread safe?](http://stackoverflow.com/questions/21500944/is-iptcpsocket-close-thread-safe) – Galimov Albert Aug 12 '14 at 08:20
  • Threads that run `io_service.run()` are user threads. The application has no direct access to Asio's internal threads. A single user thread processing the `io_service`'s event loop will be selected to use the [platform specific demultiplexing mechanism](http://www.boost.org/doc/libs/1_56_0/doc/html/boost_asio/overview/implementation.html). When events occur, the thread queues associated operations into the `io_service`, which will then demultiplex the operations to all user threads servicing the `io_service`. This [answer](http://stackoverflow.com/a/14116082/1053968) may provide details. – Tanner Sansbury Aug 16 '14 at 16:54

1 Answers1

1

Asio completely hides system dependent threads (pthreads, windows threads). It does not matter which thread is handling your code, what does matter is the ioservice.

No async code is executed at all of you do not call ioservice.run().

I hope this is of some help.

Martin Meeser
  • 2,784
  • 2
  • 28
  • 41
  • Does Asio also hide the threads running `io_service.run()`? I mean do I need to worry about racing with those threads when accessing objects in async operations, like `socket` in the question? – updogliu Aug 11 '14 at 21:48