view Implab/Parallels/WorkerPool.cs @ 15:0f982f9b7d4d promises

implemented parallel map and foreach for arrays rewritten WorkerPool with MTQueue for more efficiency
author cin
date Thu, 07 Nov 2013 03:41:32 +0400
parents b0feb5b9ad1c
children 5a4b735ba669
line wrap: on
line source

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;

namespace Implab.Parallels {
    public class WorkerPool : DispatchPool<Action> {

        MTQueue<Action> m_queue = new MTQueue<Action>();
        int m_queueLength = 0;

        public WorkerPool(int minThreads, int maxThreads)
            : base(minThreads, maxThreads) {
                InitPool();
        }

        public WorkerPool(int threads)
            : base(threads) {
                InitPool();
        }

        public WorkerPool()
            : base() {
                InitPool();
        }

        public Promise<T> Invoke<T>(Func<T> task) {
            if (task == null)
                throw new ArgumentNullException("task");
            if (IsDisposed)
                throw new ObjectDisposedException(ToString());

            var promise = new Promise<T>();

            EnqueueTask(delegate() {
                try {
                    promise.Resolve(task());
                } catch (Exception e) {
                    promise.Reject(e);
                }
            });

            return promise;
        }

        protected void EnqueueTask(Action unit) {
            Debug.Assert(unit != null);
            Interlocked.Increment(ref m_queueLength);
            m_queue.Enqueue(unit);
            // if there are sleeping threads in the pool wake one
            // probably this will lead a dry run
            WakeNewWorker();
        }

        protected override bool TryDequeue(out Action unit) {
            if (m_queue.TryDequeue(out unit)) {
                Interlocked.Decrement(ref m_queueLength);
                return true;
            }
            return false;
        }

        protected override void InvokeUnit(Action unit) {
            unit();
        }
    }
}