C++多线程执行速度减慢
我正在编写一个多线程 C++ 应用程序。当线程 A 要执行计算量非常大的操作时,它会减慢线程 B、C 和 D 的速度。如何防止这种情况发生?
I am writing a multi-threaded c++ application. When thread A has a very computationally expensive operation to perform, it slows down threads B, C, and D. How can I prevent this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在 Windows 上,您可以使用
Sleep(0)
为其他正在等待的线程释放剩余的时间片。On windows you can use
Sleep(0)
to release the remainder of your timeslice for other threads that are waiting.没有看到代码很难判断,所以我只能给你建议降低线程 A 的优先级。这可以使用 SetThreadPriority 来完成功能。
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.
请注意,您可以设置线程优先级 (
SetThreadPriority
)另外,我建议后台工作人员从队列中选择它的工作。然后,队列可以用作限制计算的一种方法:
0.02 美元
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:
$0.02
有几种方法:
Sleep(0)
,以使其更频繁地产生时间。这是廉价且懒惰的解决方案。CreateThread
时,传递CREATE_SUSPENDED
,以便线程不会立即启动。然后调用SetPriorityClass
将线程设置为较低优先级,然后调用ResumeThread
。There are a couple of ways:
Sleep(0)
in thread A's inner loop to have it yield time more frequently. This is the cheap and lazy solution.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.