Wednesday, January 31, 2007

Multithreading ThreadPool class replacement

Some very useful code for wanting a ThreadPool that actually multithreads (as .Net's builtin ThreadPool object only runs one thread at a time):

namespace Wiegand
{
    public class ThreadPool
    {
        private System.Collections.Queue _queue = new System.Collections.Queue();

        public long QueueLength()
        {
            lock (this._queue) { return this._queue.Count; }
        }
        public Object Dequeue()
        {
            lock (this._queue) { return this._queue.Dequeue(); }
        }
        public void Enqueue(Object value)
        {
            lock (this._queue) { _queue.Enqueue(value); }
        }

        public void RunThreads(int threadCount, System.Threading.ParameterizedThreadStart pts)
        {
            // now, start the threads
            // since threadpool only actually runs one thread at a time, it is not ideal for this situation
            System.Collections.Generic.List threads = new List(threadCount);
            for (int i = 1; i <= threadCount; i++)
            {
                Thread thread = new Thread(pts);
                threads.Add(thread);
                thread.Start();
            }

            foreach (System.Threading.Thread thread in threads)
            {
                thread.Join(); // wait for each to finish
            }
            // done!
        }
        public void RunThreads(int threadCount, System.Threading.ThreadStart pts)
        {
            // now, start the threads
            // since threadpool only actually runs one thread at a time, it is not ideal for this situation
            System.Collections.Generic.List threads = new List(threadCount);
            for (int i = 1; i <= threadCount; i++)
            {
                Thread thread = new Thread(pts);
                threads.Add(thread);
                thread.Start();
            }

            foreach (System.Threading.Thread thread in threads)
            {
                thread.Join(); // wait for each to finish
            }
            // done!
        }
    }
}

No comments: