Reputation: 34185
A normal worker thread runs in a loop in which it checks for available tasks in a queue and consumes them. I've seem some examples where the thread waits a couple of milliseconds when there is no available task, using std::this_thread::sleep_for()
for example. However, I want my thread to consume the tasks with minimal latency, so I don't use a sleep. Is that any bad? Should a worker thread sleep for some milliseconds when checking for tasks?
Upvotes: 2
Views: 1349
Reputation: 129374
If you "roll your own" queue or message system, one way to avoid consuming 100% cpu is to "sleep" for a bit when there's no work available. However, having some other mechanism that lets the OS take care of this for you (semaphore(s), OS-based queue such as pipe or mailbox system, or even using a network message passing mechanism, etc) would be much better, since it simplifies your application, and it allows the OS to take care of the sleeping/waking processing.
Of course, it all depends on what you are actually trying to achieve and what the expectation is - if your code is intended to run on, say, a mobile phone, not wasting CPU-cycles is critical, because that kills battery life as well as wasting CPU cycles that could be used on some other task. On the other hand, if your messaging system is in the ABS brakes of a car, and you require to measure the time of the pulses from the sensor with sub-microsecond accuracy, sleeping would be a bad idea, since your code will probably sleep for a lot longer than once pulse from the ABS sensor.
If it's in a desktop, nobody will care if your application doesn't sleep if it runs for a few seconds or even a minute or more. But if it keeps using 1 core at 100% for hours (and your app isn't producing something that is at least as valuable as the cycles wasted - obviously calculating the next largest prime number in the world or folding proteins is worth wasting cycles on. Saving 0.5 milliseconds on receiving a packet from the internet probably isn't).
Only you (and any other people involved in the project of course) will know what the design criteria is for your project. It is not something you can "ask the internet" about. The above should give you some guidance once you have figured out what your design criteria is, however.
Upvotes: 7