I have a list of items that I need to update on different intervals. The list can grow to be thousands of items long. Each item could potentially have a different interval. If I create one timer per item, am I going to saturate the system with threads? I was thinking it might be better to create one timer equal to the smallest interval in the set of items, and then on each update increment a counter, and then check to see if the counter is now equal to any other intervals. This should work provided the smallest interval is a multiple of all the other intervals. Any suggestions?
Asked
Active
Viewed 5,375 times
2 Answers
12
Boost does not use a thread per timer, it keeps a timer queue. Every timer is created with boost::asio::io_service
object that does the actual work.
This object can dispatch its work in one or more threads, when you run boost::asio::io_service::run()
explicitly from multiple threads, but there is no one-to-one correspondence between timers and threads, and Asio will not create threads behind your back.

Alex B
- 82,554
- 44
- 203
- 280
-
Ok that is good, but you say it will dispatch its work in "one or more" threads. By default if I create a thousand timers bound to one io_service, and call run on the io_service from one thread, all those timers will be performed on one new thread? Clearly they won't be performed on the calling thread when you call timer::async_wait, right? Also, despite this ability, does my design as stated seem preferable to creating many timers? Or am I in essence duplicating what the timer does anyway? – Rhubarb Mar 09 '10 at 02:00
-
6(1) Yes, if you run IO service from thread A, all timer handlers will be run on thread A. (2) Creating many timers is preferred, because it would be more maintainable and less error-prone than hand-calculating shortest interval for one timer (you'd have 1-to-1 relation b/w work items and timers). – Alex B Mar 09 '10 at 02:06
-
2PS And yes, you'd be duplicating work Asio already does for you (keeping track of earliest expiring timer). – Alex B Mar 09 '10 at 02:14
-
on windows, asio creates an extra thread for managing the timers queue. so it actually does create a single thread behind your back. – Elad Maimoni Apr 01 '23 at 04:24
1
Recent versions of Asio, Boost 1.43 and later, use the timerfd_create(2)
API on Linux for deadline_timer
s.
Changed to use timerfd for dispatching timers on Linux, when available.

Sam Miller
- 23,808
- 4
- 67
- 87