I'm new to ASIO and like to understand how thread-safety works, so that I can figure out what assumptions I can make when using ASIO APIs.
What I found out so far:
Multiple threads can run io_service.run()
.
Therefore, the handlers within a class such as socket
, might be invoked
from different threads, but only from the threads that execute io_service.run()
.
Let's assume that a socket
has some internal state that must be protected
from concurrent access.
The socket
would wrap its handlers with a strand
, which serializes the execution
of the handlers. It has essentially the same effect as acquiring a mutex in each
handler, but with better performance.
But socket
also has public methods, such as socket.async_write_some()
. It
too might be invoked from different threads.
Let's assume that socket.async_write_some()
accesses the same internal state,
so some protection mechanism is needed.
How do public methods access the internal state in a safe way?
can
strand
be used to serialize invocations of public methods?invoke
post([]{ /* actual implementation of the method goes here */})
within the public method?use a mutex in addition to the strand?
What assumptions can I make when invoking public APIs?
Can I assume that a socket
protects it's internal state, even if I invoke it from a background thread that does not invoke io_service.run()
?
If so, is there some documentation for that? I'd rather not depend on an undocumented implementation detail.