C++ Multi-Thread Execution Speed Slow-Down
I am writing a multi-threaded c++ application. When thread A has a very computationally expensive operation to perform, it slows 开发者_StackOverflow中文版down threads B, C, and D. How can I prevent this?
On windows you can use Sleep(0)
to release the remainder of your timeslice for other threads that are waiting.
Hard to tell without seeing code so I can only give you the advice to lower Thread A's priority. This can be done using the SetThreadPriority function.
Note that you can set the thread priorities (SetThreadPriority
)
Also, I advice the backgroundworker picks it's work from a queue. The queue can then be used as a way to throttle the calculations:
- you can configure how many 'tasks' are taken from the queue for processing in one swoop
- you can lock the queue (use semaphores + condition event) so you can temporarily prevent new tasks from being picked up.
- you can now distribute the load across more workers (say if thread B, C, D are temporarily idle, they can start to lift the work off thread A; very useful on a Quad-core + desktop)
$0.02
There are a couple of ways:
- As RedX suggested, add
Sleep(0)
in thread A's inner loop to have it yield time more frequently. This is the cheap and lazy solution. - Better would be to change the thread priority. When you call
CreateThread
, passCREATE_SUSPENDED
so that the thread does not start immediately. Then callSetPriorityClass
to set the thread to a lower priority, followed byResumeThread
.
You might also want to look at having your compute-bound thread yield the processor to other threads. See this post for various ways to do this.
精彩评论