4 ms·
Both of these examples exhibit the "busy waiting" anti pattern where a thread is waiting for something in a loop with a sleep or yield in it. This consumes CPU
by exDM69 12y ago
Both of these examples exhibit the "busy waiting" anti pattern where a thread is waiting for something in a loop with a sleep or yield in it. This consumes CPU time, power and resources and may be sleeping more than necessary. The proper fix for this is to wait on a condition variable, which will make sure the thread remains inactive when idle.
This may be fine for a trivial example of std::thread and std::mutex but you should almost never do this in practice (there are some exceptions in kernel space when waiting for an I/O device).
I have a few useful rules of thumb when doing multi threaded programming which I want to share:
1) Almost every mutex should be coupled with one or (usually) more condition variables
2) A mutex variable named "mutex" is a code smell. Ditto for condition variables named "cond". They usually have an easy-to-describe function such as "queue_lock", "not_full" or "not_empty".
- functional_test 12y agoI'll start by saying that I agree with almost everything you've said. I can think of one time where a loop with a sleep might be appropriate though -- if you have something, perhaps some IO channel like a log, and you want it flushed regularly, but not every time a write is performed. With a long enough sleep (>100ms) the performance overhead ought to be low. Is there a better way to design that though?
- std_throwaway 12y agoIn that case you don't want to sleep. You want to wait until a condition (new data) or a timeout (100ms) occurs. The reasoning is that you don't know how much data will arrive in the next 100ms and if you sleep either a buffer could overrun or something else could block. Therefore you need to flush the buffer either when enough data has accumulated or if a timeout has occured.
- functional_test 12y agoI can see where you're coming from. For my particular apication that's not a concern (and I have sequence numbers to know when I've dropped data).
- otikik 12y ago> The proper fix for this is to wait on a condition variable, which will make sure the thread remains inactive when idle. In case that phrase confuses others reading that: a Condition Variable is a sync-related construct - like Mutex or Semaphore. It does not mean "a regular variable that you put on an if". A very bad name for the concept in my opinion. http://en.cppreference.com/w/cpp/thread/condition_variable http://en.cppreference.com/w/cpp/thread/condition_variable