寻求MT设计模式的帮助

时间:2009-12-31 06:49:39

标签: multithreading

我有一个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来实现上述目标。该 应遵循以下约束

  1. 主线程要求之前处理所有工作项 它可以继续。所以我认为像上面的等待构造 是必需的
  2. 我想创建与处理器一样多的线程(即不是1000个线程 一次)
  3. 此外,我不想创建1000个不同的事件,传递给工人 线程,并使用QueueUserWorkitem API等待所有事件 否则
  4. Exisitng代码在C ++中。更喜欢C ++,因为我不知道c#
  5. 我怀疑以上是一种非常常见的模式并且正在寻找 来自你们的人。

1 个答案:

答案 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