class Process
{
static void Main(string[] args)
{
int threads = 0;
int processes = 0;
Console.WriteLine("Total number of processes:");
processes = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter number of parallel threads:");
threads = Convert.ToInt32(Console.ReadLine());
ManualResetEvent[] events = new ManualResetEvent[threads];
int k = 0, innercount = 0;
//----running in bunches
do
{
for (int l = 0; l < threads; l++)
{
if (k < threads)
{
events[l] = new ManualResetEvent(false);
Runner r = new Runner(events[l], innercount);
new Thread(new ThreadStart(r.Run)).Start();
Console.WriteLine("running start...{0}", innercount);
k++;
innercount++;
}
}
WaitHandle.WaitAny(events);
k--;
Console.WriteLine("Decrement counter...{0}", k);
}
while (innercount < processes);
WaitHandle.WaitAll(events);
Console.WriteLine("All finished!");
Console.ReadLine();
}
}
class Runner
{
static readonly object rngLock = new object();
static Random rng = new Random();
ManualResetEvent ev;
int id;
internal Runner(ManualResetEvent ev, int id)
{
this.ev = ev;
this.id = id;
}
internal void Run()
{
int sleepTime;
lock (rngLock)
{
sleepTime = rng.Next(2000);
}
Thread.Sleep(sleepTime);
Console.WriteLine("Thread Runner {0}",
id);
if (ev.Set())
{
Console.WriteLine("release thread...{0}", id);
}
}
}
我必须运行多个线程。如果一个线程完成然后启动另一个线程。问题是它同时启动了所有进程。(似乎这种情况不能正常工作 WaitHandle.WaitAny(events);)
1:如果有 20 个线程正在运行,那么当一个线程从 20s 线程释放时,将启动第 21 个线程。
2:不使用线程池可以使用EventWaitHandler来完成。