gpt4 book ai didi

c# - 让工作线程等待任务的 CPU 效率最高的方法是什么?

转载 作者:太空狗 更新时间:2023-10-29 22:35:11 24 4
gpt4 key购买 nike

在我当前的 C#/NET 3.5 应用程序中,我有一个任务队列(线程安全)并且我有 5 个工作线程必须不断地在队列中查找任务。如果任务可用,任何一个工作人员都会使任务出队并采取所需的操作。

我的工作线程类如下:

public class WorkerThread
{
//ConcurrentQueue is my implementation of thread safe queue
//Essentially just a wrapper around Queue<T> with synchronization locks
readonly ConcurrentQueue<CheckPrimeTask> mQ;
readonly Thread mWorker;
bool mStop;

public WorkerThread (ConcurrentQueue<CheckPrimeTask> aQ) {
mQ = aQ;
mWorker = new Thread (Work) {IsBackground = true};
mStop = false;
}

private void Work () {
while (!mStop) {
if (mQ.Count == 0) {
Thread.Sleep (0);
continue;
}

var task = mQ.Dequeue ();
//Someone else might have been lucky in stealing
//the task by the time we dequeued it!!
if (task == null)
continue;

task.IsPrime = IsPrime (task.Number);
task.ExecutedBy = Thread.CurrentThread.ManagedThreadId;
//Ask the threadpool to execute the task callback to
//notify completion
ThreadPool.QueueUserWorkItem (task.CallBack, task);
}
}

private bool IsPrime (int number) {
int limit = Convert.ToInt32 (Math.Sqrt (number));
for (int i = 2; i <= limit; i++) {
if (number % i == 0)
return false;
}

return true;
}

public void Start () {
mStop = false;
mWorker.Start ();
}

public void Stop () {
mStop = true;
}
}

问题是当队列为空时,它消耗了太多的 CPU(将近 98%)。我尝试使用 AutoResetEvent 通知工作人员队列已更改。因此,他们有效地等待该信号设置。它已将 CPU 降低到接近 0%,但我不完全确定这是否是最佳方法。您能否建议一种更好的方法来保持线程空闲而不影响 CPU 使用率?

最佳答案

查看 BlockingQueue 的这个实现.如果队列为空,它使用 Monitor.Wait() 使线程进入休眠状态。添加项目时,它会使用 Monitor.Pulse() 唤醒在空队列上休眠的线程。

另一种技术是使用 semaphore .每次将项目添加到队列时,调用 Release()。当您需要队列中的项目时,请调用 WaitOne()。

关于c# - 让工作线程等待任务的 CPU 效率最高的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2062637/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com