.NET提供,你可以使用一個線程池。 System.Threading.ThreadPool.QueueUserWorkItem()
告訴池中的線程爲你做一些工作。
如果我設計這個,我不會專注於線程映射到您的硬件資源。相反,我會爲每個HW資源公開一個可鎖定的對象 - 這可以簡單地是一個數組或5個對象的隊列。然後,對於您的每一位計算,請撥打QueueUserWorkItem()
。在傳遞給QUWI的方法中,找到下一個可用的可鎖定對象並將其鎖定(也就是說,將其解除鎖定)。使用HW資源,然後重新排列對象,退出QUWI方法。
無論你打電話給QUWI多少次,最多可鎖定5個鎖,每個鎖都可以訪問您的特殊硬件設備的一個實例。
doc page for Monitor.Enter()
顯示瞭如何創建一個可以被多個工作人員訪問的安全(阻塞)隊列。在.NET 4.0中,你會使用the builtin BlockingCollection - 這是一回事。
這基本上是你想要的。除了不要撥打Thread.Create()
。使用線程池。
舉:Advantage of using Thread.Start vs QueueUserWorkItem
// assume the SafeQueue class from the cited doc page.
SafeQueue<SpecialHardware> q = new SafeQueue<SpecialHardware>()
// set up the queue with objects protecting the 5 magic stones
private void Setup()
{
for (int i=0; i< 5; i++)
{
q.Enqueue(GetInstanceOfSpecialHardware(i));
}
}
// something like this gets called many times, by QueueUserWorkItem()
public void DoWork(WorkDescription d)
{
d.DoPrepWork();
// gain access to one of the special hardware devices
SpecialHardware shw = q.Dequeue();
try
{
shw.DoTheMagicThing();
}
finally
{
// ensure no matter what happens the HW device is released
q.Enqueue(shw);
// at this point another worker can use it.
}
d.DoFollowupWork();
}
你說的5個獨立的硬件是什麼意思?你想分發超過5臺機器? –
我在想象他有5件事情,例如機載協處理器設備。也許他們是特殊的硬件加密設備。無論如何 - 他們會做一些計算密集的工作,比方說。而且他們每次只能做一件事。它們不是遠程通用計算機,所以這不是分佈式計算的問題。相反,它們是專用資源,由單個程序使用。 – Cheeso