我有一个1000个工作项和一个n-proc机器的队列(假设n = 4)。主线程一次产生n(= 4)个工作线程(外部25个) 迭代)并在处理之前等待所有线程完成 下一个n(= 4)项,直到整个队列被处理
for(i= 0 to queue.Length / numprocs)
for(j= 0 to numprocs)
{
CreateThread(WorkerThread,WorkItem)
}
WaitForMultipleObjects(threadHandle[])
每个(工人)线程所做的工作不是同质的。因此 1批(n)如果线程1花费1000秒做工作,其余3分钟 线程只有1秒,上面的设计是低效的,因为1秒后 其他3个处理器都空转。此外没有汇集 - 1000 正在创建不同的线程
我如何使用NT线程池(我不够熟悉 - 因此 冗长的问题)和QueueUserWorkitem来实现上述目标。该 应遵循以下约束
我怀疑以上是一种非常常见的模式并且正在寻找 来自你们的人。
答案 0 :(得分:0)
我不是C ++程序员,所以我会给你一些半路伪代码
tcount = 0
maxproc = 4
while queue_item = queue.get_next() # depends on implementation of queue
# may well be:
# for i=0; i<queue.length; i++
while tcount == maxproc
wait 0.1 seconds # or some other interval that isn't as cpu intensive
# as continously running the loop
tcount += 1 # must be atomic (reading the value and writing the new
# one must happen consecutively without interruption from
# other threads). I think ++tcount would handle that in cpp.
new thread(worker, queue_item)
function worker(item)
# ...do stuff with item here...
tcount -= 1 # must be atomic