caloggins
11/29/2012 - 3:15 AM

Basic threading class.

Basic threading class.

    public class LocalThreadPool
    {
        private readonly object threadLock = new object();
        private readonly Thread[] workers;
        private readonly Queue<Action> actionQueue = new Queue<Action>();

        public LocalThreadPool()
        {
            workers = new Thread[5];
            for (var i = 0; i < 5; i++)
                (workers[i] = new Thread(Consume)).Start();
        }

        public void Enqueue(Action action)
        {
            lock(threadLock)
            {
                actionQueue.Enqueue(action);
                Monitor.Pulse(threadLock);
            }
        }

        private void Consume()
        {
            while(true)
            {
                Action item;
                
                lock(threadLock)
                {
                    while (actionQueue.Count == 0)
                        Monitor.Wait(threadLock);
                    item = actionQueue.Dequeue();
                }

                if(item == null)
                    return;
                item();
            }
        }

        public void Shutdown(bool waitForWorkers)
        {
#pragma warning disable 168
            foreach (var worker in workers)
                Enqueue(null);
#pragma warning restore 168


            if (waitForWorkers)
                foreach (var worker in workers)
                    worker.Join();
        }
    }