Skip to content

Instantly share code, notes, and snippets.

@hagbarddenstore
Last active December 11, 2015 08:19
Show Gist options
  • Save hagbarddenstore/4572459 to your computer and use it in GitHub Desktop.
Save hagbarddenstore/4572459 to your computer and use it in GitHub Desktop.
A simple ThreadPool implementation. Not to be used, but to explain the concepts.
class ThreadPool
{
private static readonly object LockObject = new object();
private static readonly Queue<Action> _work = new Queue<Action>();
private static readonly List<Thread> _workers = new List<Thread>();
static ThreadPool()
{
for (var i = 0; i < 5; i++)
{
var thread = new Thread(DoWork);
_workers.Add(thread);
}
}
public void QueueWork(Action action)
{
lock (LockObject)
{
_work.Enqueue(action);
}
}
private static void DoWork()
{
while (true)
{
Action action;
lock (LockObject)
{
action = _work.Dequeue();
}
if (action != null)
{
action();
}
Thread.Sleep(1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment