开发者

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, pass CREATE_SUSPENDED so that the thread does not start immediately. Then call SetPriorityClass to set the thread to a lower priority, followed by ResumeThread.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜