Last active
December 11, 2015 08:19
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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