Thanks Gavin,
On 9/2/19, Gavin Lambert via Boost
On 2/09/2019 13:06, JH wrote:
Does io_service create threads for running timers? My application is running a single thread, but if io_service creates multiple threads for running timer, I must use the mutex or atomic lock.
Don't top-post.
As is documented, while Asio may or may not create internal threads for various purposes, it does guarantee that the I/O callback functions (including timer callbacks) are only ever called on a thread which is currently executing run() or equivalent on the same service/context.
Yes, it is a single thread from my run function, there is no thread create, so that did guarantee the single thread to run the timer one by one in order as I original understanding.
If there is only one such thread (an "implicit strand"), then you don't need locks to protect things that are only accessed from an I/O callback, even if there is more than one such callback (provided that all callbacks were registered on the same service/context).
Each timer has only one callback.
You may still need locks to protect things that are accessed from both callbacks and initiating functions (or elsewhere), unless you ensure that initiating functions delegate their concurrent work to the I/O thread via dispatch()/post().
Does that mean if any callbacks to involve IO write / read, it still need locks? What about just to copy shared global buffer to own local buffers? The two timer callbacks only copy contents from one globe buffer to its own local buffer, then use own local buffer to write file, I think that should be safe, no locks need. Another timer callback is to read / write chip registers from a serial line, that looks like must either lock the global buffer or copy global buffer to a local buffer, right? Thanks Gavin.