83 lines
1.9 KiB
C#
83 lines
1.9 KiB
C#
using System;
|
|
using System.Threading;
|
|
using System.Collections.Generic;
|
|
namespace ln.http.threads
|
|
{
|
|
public delegate void JobDelegate();
|
|
|
|
public class Pool
|
|
{
|
|
public int Timeout { get; set; } = 15000;
|
|
|
|
ISet<Thread> threads = new HashSet<Thread>();
|
|
Queue<JobDelegate> queuedJobs = new Queue<JobDelegate>();
|
|
HashSet<Thread> idleThreads = new HashSet<Thread>();
|
|
|
|
public Pool()
|
|
{
|
|
}
|
|
|
|
private void AllocateThread()
|
|
{
|
|
Thread thread = new Thread(pool_thread);
|
|
thread.Start();
|
|
}
|
|
|
|
public void Enqueue(JobDelegate job)
|
|
{
|
|
lock (this)
|
|
{
|
|
queuedJobs.Enqueue(job);
|
|
|
|
if (idleThreads.Count == 0)
|
|
{
|
|
AllocateThread();
|
|
}
|
|
else
|
|
{
|
|
Monitor.Pulse(this);
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
private void pool_thread()
|
|
{
|
|
Thread me = Thread.CurrentThread;
|
|
|
|
try
|
|
{
|
|
JobDelegate job = null;
|
|
do
|
|
{
|
|
lock (this)
|
|
{
|
|
if (queuedJobs.Count == 0)
|
|
{
|
|
idleThreads.Add(me);
|
|
bool s = Monitor.Wait(this, Timeout);
|
|
idleThreads.Remove(me);
|
|
if (!s)
|
|
break;
|
|
}
|
|
job = queuedJobs.Dequeue();
|
|
}
|
|
|
|
job();
|
|
|
|
} while (true);
|
|
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
Console.WriteLine("Exception in worker thread: {0}", e);
|
|
}
|
|
|
|
lock (this)
|
|
{
|
|
threads.Remove(me);
|
|
}
|
|
}
|
|
}
|
|
}
|