线程占用大量CPU
我正在使用 Thread 来帮助在 perl 中执行线程;我想说我对线程相当陌生。
我的程序中有一个名为“最大线程”的变量。如果线程数量低于这个数字,就会提示新的线程。我使用 while 循环将当前现有线程数与最大线程变量进行比较。
我假设 while 循环是消耗我的 cpu 的东西。
无论如何,我可以让“老板”或“经理”线程(核心线程)在安排和管理线程时不占用那么多的CPU吗?如果我的 CPU 仅仅因为管理器线程而提高,那么线程根本没有任何意义!
I'm using Thread to help do threads in perl; I'd say I'm fairly new to threading.
I have a variable in my program called "max threads". If the number of threads falls below this number, it will prompt a new one. I'm using a while loop to compare the current number of existing threads to the maximum threads variable.
I'm assuming that the while loop is the thing consuming my cpu.
Is there anyway that I can have the 'boss' or 'manager' thread (The core thread) not take up as much cpu while arranging and managing threads? If my CPU is raising just because of the manager thread, then there's ultimately no point to threading at all!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您想保留当前模型,则应该有某种信号(可能是信号量),当工作人员太多时,线程启动器可以阻止该信号。
一个更简单的模型是拥有一个工作人员池,并通过 Thread::Queue 为他们提供工作。
If you want to keep the current model, you should have some kind of signal (probably a semaphore) on which the thread launcher can block when there are too many workers.
A much simpler model is to have a pool of workers, and given them work via a Thread::Queue.
我不使用 Perl,但从一般异步编程的角度来看,您需要一个不会阻塞主线程的线程池管理器,并且这可以通过多种方式完成。一方面,您可以专用一个线程(耶!)来执行类似以下操作(伪代码):
操作系统或抽象的运行时库通常会提供某种等待函数,该函数会暂停线程,直到达到特定数量为止。时间已经过去(因此在此期间不占用调度程序资源)。
或者,如果您的程序是事件驱动的(如在 GUI 环境中),您可以通过发布计时器消息来在主线程之外执行类似的池管理,这是操作系统通常提供的另一项服务。
I don't use Perl, but speaking from a general asynchronous programming perspective, you want a thread pool manager that isn't clogging up the main thread, and this can be accomplished multiple ways. For one thing, you can dedicate a thread (yay!) to doing something like this (pseudocode):
The OS, or your abstracted run-time library, will generally supply some kind of wait function that halts the thread until a specific amount of time has passed (thus taking up no scheduler resource during that time).
Alternatively, if your program is event-driven (as in a GUI environment), you could do similar pool management off the main thread by posting yourself timer messages, which is another service generally supplied by the OS.
与其他语言相比,Perl 线程是重量级的。他们需要大量资源来启动;尝试预先启动您需要的所有线程并保持它们运行。每次执行异步任务时都启动新线程,效率非常低。
Perl threads are heavy-weight compared to other languages. They take a lot of resources to start; try to start all the threads you need up front and just keep them running. Starting new threads every time you have an asynchronous task to do will be very inefficient.