把线保持最佳吗? [英] Is putting thread on hold optimal?

查看:120
本文介绍了把线保持最佳吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

应用程序具有辅助线程。这个线程并不意味着一直运行,但主流程可以很频繁地调用。

Application has an auxiliary thread. This thread is not meant to run all the time, but main process can call it very often.

所以,我的问题是,在CPU性能方面更为优化:当线程未被使用或保持活动时挂起线程,并使用WaitForSingleObject函数等待来自主进程的信号。

So, my question is, what is more optimal in terms of CPU performance: suspend thread when it is not being used or keep it alive and use WaitForSingleObject function in order to wait for a signal from main process?

推荐答案

在使用的CPU资源方面,两个解决方案都是一样的 - 挂起的线程和WaitForSingleObject中没有发出信号的对象的线程根本没有CPU周期。

In terms of CPU resources used, both solutions are the same - the thread which is suspended and thread which is waiting in WaitForSingleObject for an object which is not signalled both get no CPU cycles at all.

这就是说,WaitForSingleObject几乎总是一个优先的解决方案,因为使用它的代码将更加自然 - 更容易阅读,更容易做到。暂停/恢复线程可能是危险的,因为您需要非常小心,以确保您知道您暂停线程处于挂起状态将不会有任何伤害(假设挂起当前持有互斥体的线程)的线程。

That said, WaitForSingleObject is almost always a prefered solution because the code using it will be much more "natural" - easier to read, and easier to make right. Suspending/Resuming threads can be dangerous, because you need to take a lot of care to make sure you know you are suspending a thread in a state where suspending it will do no harm (imagine suspending a thread which is currently holding a mutex).

这篇关于把线保持最佳吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆