Beispiel #1
0
        public static void TestList(ListAggregation a, long[] vals, string msg)
        {
            long               bestTimeMillis = int.MaxValue;
            const int          NRUNS          = 10;
            IEnumerable <long> it             = null;
            int threadsUsed = int.MaxValue;

            for (int i = 0; i < NRUNS; ++i)
            {
                WorkerThreadReport.SetRefTime();
                Stopwatch sw = Stopwatch.StartNew();

                it = a(vals, vals.Length);

                sw.Stop();
                if (sw.ElapsedMilliseconds < bestTimeMillis)
                {
                    bestTimeMillis = sw.ElapsedMilliseconds;
                }
                int used = WorkerThreadReport.UsedThreads;
                if (used < threadsUsed)
                {
                    threadsUsed = used;
                }
            }


            Console.WriteLine("{0}: total primes is {1}, done in {2} ms!",
                              msg, it.Count(), bestTimeMillis);
            Console.WriteLine("{0} threads were used!", threadsUsed);
        }
Beispiel #2
0
        public static IEnumerable <long> GetPrimesParTasks(long[] vals, int size)
        {
            LinkedList <long> primes = new LinkedList <long>();
            //ConcurrentQueue<long> primes = new ConcurrentQueue<long>();


            List <Task> tasks = new List <Task>();

            for (int i = 0; i < size; ++i)
            {
                Task t = Task.Factory.StartNew((o) => {
                    WorkerThreadReport.RegisterWorker();
                    long val = (long)o;
                    if (IsPrime(val))
                    {
                        lock (primes) { primes.AddLast(val); }
                    }
                }, vals[i]);

                tasks.Add(t);
            }
            Task.WaitAll(tasks.ToArray());

            return(primes);
        }
Beispiel #3
0
        public static void Test()
        {
            int[] vals = new int[50000000];
            InitVals(vals);
            int[] vals1 = (int[])vals.Clone();
            int[] vals2 = (int[])vals.Clone();

            StatsInit();
            Stopwatch sw = Stopwatch.StartNew();

            SeqSort(vals, 0, vals.Length - 1);
            sw.Stop();
            Console.WriteLine("sequential sort in {0}ms", sw.ElapsedMilliseconds);
            StatsShow();

            StatsInit();
            sw.Restart();

            // sort using threadpool directly and parallel recurrence level=4
            SortTP(vals1, 2);
            sw.Stop();
            Console.WriteLine("threadpool sort in {0}ms", sw.ElapsedMilliseconds);
            StatsShow();

            StatsInit();
            sw.Restart();
            // sort using tasks and parallel recurrence level=6
            SortTask(vals2, 8);
            sw.Stop();
            Console.WriteLine("task sort in {0}ms", sw.ElapsedMilliseconds);
            StatsShow();

            WorkerThreadReport.ShutdownWorkerThreadReport();
        }
Beispiel #4
0
        public static IEnumerable <long> GetPrimesParAggregation(long[] vals, int size)
        {
            LinkedList <List <long> > primes =
                new LinkedList <List <long> >();

            ParallelLoopResult res = Parallel.For(
                0,
                size,
                () => new List <long>(size / 50),
                (i, s, l) => {
                ParallelLoopState state = s;

                WorkerThreadReport.RegisterWorker();
                if (IsPrime(vals[i]))
                {
                    l.Add(vals[i]);
                }
                return(l);
            },
                (l) => {
                lock (primes) {
                    primes.AddLast(l);
                }
            });

            var count = primes.Count();

            return(primes.SelectMany(s => s));
        }
Beispiel #5
0
        private static void StatsCollect()
        {
            WorkerThreadReport.RegisterWorker();
            int usedThreads = WorkerThreadReport.UsedThreads;
            int wi          = Interlocked.Increment(ref WorkUnits);

            Console.WriteLine("In work Item {0}, UsedThreads={1}",
                              wi, usedThreads);
        }
Beispiel #6
0
        public static void Main(String[] args)
        {
            //TestTPL0();

            //TestCountPrimes();

            //Console.WriteLine();
            TestGetPrimes();

            WorkerThreadReport.ShutdownWorkerThreadReport();
        }
Beispiel #7
0
        public static IEnumerable <long> GetPrimesParPLinq(long[] vals, int size)
        {
            var primes = vals.AsParallel().
                         Take(size).
                         Where((v) => {
                WorkerThreadReport.RegisterWorker();
                return(IsPrime(v));
            });

            primes.Count();
            return(primes);
        }
Beispiel #8
0
        public static IEnumerable <long> GetPrimesParFor(long[] vals, int size)
        {
            //LinkedList<long> primes = new LinkedList<long>();
            List <long> primes = new List <long>();

            Parallel.ForEach(vals, (v) => {
                WorkerThreadReport.RegisterWorker();
                if (IsPrime(v))
                {
                    lock (primes) { primes.Add(v); }
                }
            });
            return(primes);
        }
Beispiel #9
0
        // Thread that monitors the worker thread's exit.
        private static void ExitMonitorThreadBody()
        {
            int rcount;

            do
            {
                List <WorkerThreadReport> exited = null;
                lock (_lock)
                {
                    rcount = reports.Count;
                    for (int i = 0; i < reports.Count;)
                    {
                        WorkerThreadReport r = reports[i];
                        if (!r.theThread.IsAlive)
                        {
                            reports.RemoveAt(i);
                            if (exited == null)
                            {
                                exited = new List <WorkerThreadReport>();
                            }
                            r.exitTime = Environment.TickCount;
                            exited.Add(r);
                        }
                        else
                        {
                            i++;
                        }
                    }
                }
                if (exited != null)
                {
                    foreach (WorkerThreadReport r in exited)
                    {
                        Console.WriteLine("--worker #{0} exited after {1} s of inactivity",
                                          r.theThreadId, (r.exitTime - r.timeOfLastUse) / 1000);
                    }
                }

                // sleep for a while.
                try
                {
                    Thread.Sleep(50);
                }
                catch (ThreadInterruptedException)
                {
                    return;
                }
            } while (true);
        }
Beispiel #10
0
        public static IEnumerable <long> GetPrimesParForPartition(long[] vals, int size)
        {
            //LinkedList<long> primes = new LinkedList<long>();
            List <long> primes = new List <long>();

            Parallel.ForEach(Partitioner.Create(0, size), (v) => {
                WorkerThreadReport.RegisterWorker();
                //Console.WriteLine("Range({0},{1})", v.Item1, v.Item2);
                for (int i = v.Item1; i < v.Item2; ++i)
                {
                    if (IsPrime(vals[i]))
                    {
                        lock (primes) { primes.Add(vals[i]); }
                    }
                }
            });
            return(primes);
        }
Beispiel #11
0
        public static IEnumerable <long> GetPrimesParTP(long[] vals, int size)
        {
            LinkedList <long> primes = new LinkedList <long>();


            List <Task>    tasks = new List <Task>();
            CountdownEvent done  = new CountdownEvent(size);

            for (int i = 0; i < size; ++i)
            {
                ThreadPool.QueueUserWorkItem((o) => {
                    WorkerThreadReport.RegisterWorker();
                    long val = (long)o;
                    if (IsPrime(val))
                    {
                        lock (primes) { primes.AddLast(val); }
                    }
                    done.Signal();
                }, vals[i]);
            }
            done.Wait();

            return(primes);
        }
Beispiel #12
0
    static void Main(String[] args)
    {
        int minWorker, minIocp, maxWorker, maxIocp;

        if (args.Length != 1 || !(args[0].Equals("-cpu") || args[0].Equals("-io")))
        {
            Console.WriteLine("usage: ThreadPoolMonitor [-cpu | -io]");
            return;
        }

        bool cpuBoundWorkload = args[0].Equals("-cpu");

        if (cpuBoundWorkload)
        {
            Console.WriteLine("--Monitor the .NET Framework's Thread Pool using a CPU-bound workload");
        }
        else
        {
            Console.WriteLine("--Monitor the .NET Framework's Thread Pool using a I/O-bound workload");
        }

        ThreadPool.GetMinThreads(out minWorker, out minIocp);
        ThreadPool.GetMaxThreads(out maxWorker, out maxIocp);

        //ThreadPool.SetMinThreads(2 * Environment.ProcessorCount, minIocp);
        Console.WriteLine("--processors: {0}; min/max workers: {1}/{2}; min/max iocps: {3}/{4}",
                          Environment.ProcessorCount, minWorker, maxWorker, minIocp, maxIocp);

        Console.Write("--hit <enter> to start, and then <enter> again to terminate...");
        Console.ReadLine();

        for (int i = 0; i < ACTION_COUNT; i++)
        {
            ThreadPool.QueueUserWorkItem((targ) => {
                WorkerThreadReport.RegisterWorker();
                int tid = Thread.CurrentThread.ManagedThreadId;
                Console.WriteLine($"-->Action({targ:D2}, #{tid:D2})");
                for (int n = 0; n < REPEAT_FOR; n++)
                {
                    WorkerThreadReport.RegisterWorker();
                    if (cpuBoundWorkload)
                    {
                        Thread.SpinWait(2500000);               // CPU-bound workload
                    }
                    else
                    {
                        Thread.Sleep(50);                                                       // I/O-bound workload
                    }
                }
                Console.WriteLine($"<--Action({targ:D2}, #{tid:00})");
            }, i);
        }
        int delay = 50;

        do
        {
            int till = Environment.TickCount + delay;
            do
            {
                if (Console.KeyAvailable)
                {
                    goto Exit;
                }
                Thread.Sleep(15);
            } while (Environment.TickCount < till);
            delay += 50;

            //
            // Comment the next statement to allow worker thread retirement!
            //

            /*
             * ThreadPool.QueueUserWorkItem(_ => {
             *      WorkerThreadReport.RegisterWorker();
             *      Console.WriteLine("ExtraAction() --><-- on worker thread #{0}", Thread.CurrentThread.ManagedThreadId);
             * });
             */
        } while (true);
Exit:
        Console.WriteLine($"-- {WorkerThreadReport.CreatedThreads} worker threads were injected");
        WorkerThreadReport.ShowThreads();
        WorkerThreadReport.ShutdownWorkerThreadReport();
    }
    static void Main(String[] args)
    {
        int minWorker, minIocp, maxWorker, maxIocp;

        MyOptions o = new MyOptions();

        try {
            o.load(args);
        }
        catch (Exception) {
            o.usage(); Environment.Exit(1);
        }

        Console.WriteLine("Options:");
        Console.WriteLine(o);

        if (o.blocking)
        {
            Console.WriteLine("\n-- Monitor .NET Thread Pool using a I/O-bound load\n");
        }
        else
        {
            Console.WriteLine("\n-- Monitor .NET Thread Pool using a CPU-bound load\n");
        }

        WorkerThreadReport.Verbose = true;
        ThreadPool.GetMinThreads(out minWorker, out minIocp);
        ThreadPool.GetMaxThreads(out maxWorker, out maxIocp);

        //ThreadPool.SetMinThreads(2 * Environment.ProcessorCount, minIocp);
        Console.WriteLine("-- processors: {0}; min/max workers: {1}/{2}; min/max iocps: {3}/{4}\n",
                          Environment.ProcessorCount, minWorker, maxWorker, minIocp, maxIocp);

        Console.Write("--Hit <enter> to start, and then <enter> again to terminate...");
        Console.ReadLine();

        for (int i = 0; i < o.nactions; i++)
        {
            ThreadPool.QueueUserWorkItem((targ) => {
                WorkerThreadReport.RegisterWorker();
                int tid = Thread.CurrentThread.ManagedThreadId;
                Console.WriteLine("-->Action({0}, #{1:00})", targ, tid);
                for (int n = 0; n < o.ntries; n++)
                {
                    WorkerThreadReport.RegisterWorker();
                    if (!o.blocking)
                    {
                        Thread.SpinWait(o.execTime);                                    // CPU-bound load
                    }
                    else
                    {
                        Thread.Sleep(o.blockTime);          // I/O-bound load
                    }
                }
                Console.WriteLine("<--Action({0}, #{1:00})", targ, tid);
            }, i);
            Thread.Sleep(o.injectionPeriod);
        }
        int delay = 50;

        do
        {
            int till = Environment.TickCount + delay;
            do
            {
                if (Console.KeyAvailable)
                {
                    goto Exit;
                }
                Thread.Sleep(15);
            } while (Environment.TickCount < till);
            delay += 50;

            //
            // Comment the next statement to allow worker thread retirement!
            //

            /*
             *          ThreadPool.QueueUserWorkItem(_ => {
             *                  WorkerThreadReport.RegisterWorker();
             *                  Console.WriteLine("ExtraAction() --><-- on worker thread #{0}", Thread.CurrentThread.ManagedThreadId);
             *          });
             */
        } while (true);
Exit:
        Console.WriteLine("-- {0} worker threads were injected", WorkerThreadReport.CreatedThreads);
        WorkerThreadReport.ShowThreads();
        WorkerThreadReport.ShutdownWorkerThreadReport();
    }
Beispiel #14
0
 private static void StatsInit()
 {
     WorkUnits = 0;
     WorkerThreadReport.SetRefTime();
 }
Beispiel #15
0
    static void Main()
    {
        int minWorker, minIocp, maxWorker, maxIocp;

#if CPU_BOUND_LOAD
        Console.WriteLine("\n-- Monitor .NET Thread Pool using a CPU-bound load\n");
#else
        Console.WriteLine("\n-- Monitor .NET Thread Pool using a I/O-bound load\n");
#endif

        ThreadPool.GetMinThreads(out minWorker, out minIocp);
        ThreadPool.GetMaxThreads(out maxWorker, out maxIocp);

        //ThreadPool.SetMinThreads(2 * Environment.ProcessorCount, minIocp);
        Console.WriteLine("-- processors: {0}; min/max workers: {1}/{2}; min/max iocps: {3}/{4}\n",
                          Environment.ProcessorCount, minWorker, maxWorker, minIocp, maxIocp);

        Console.Write("--Hit <enter> to start, and then <enter> again to terminate...");
        Console.ReadLine();

        for (int i = 0; i < ACTION_COUNT; i++)
        {
            ThreadPool.QueueUserWorkItem((targ) => {
                WorkerThreadReport.RegisterWorker();
                int tid = Thread.CurrentThread.ManagedThreadId;
                Console.WriteLine("-->Action({0}, #{1:00})", targ, tid);
                for (int n = 0; n < REPEAT_FOR; n++)
                {
                    WorkerThreadReport.RegisterWorker();
#if CPU_BOUND_LOAD
                    Thread.SpinWait(5000000);       // CPU-bound load
#else
                    Thread.Sleep(10);               // I/O-bound load
#endif
                }
                Console.WriteLine("<--Action({0}, #{1:00})", targ, tid);
            }, i);
        }
        int delay = 50;
        do
        {
            int till = Environment.TickCount + delay;
            do
            {
                if (Console.KeyAvailable)
                {
                    goto Exit;
                }
                Thread.Sleep(15);
            } while (Environment.TickCount < till);
            delay += 50;

            //
            // Comment the next statement to allow worker thread retirement!
            //

            /*
             *          ThreadPool.QueueUserWorkItem(_ => {
             *                  WorkerThreadReport.RegisterWorker();
             *                  Console.WriteLine("ExtraAction() --><-- on worker thread #{0}", Thread.CurrentThread.ManagedThreadId);
             *          });
             */
        } while (true);
Exit:
        Console.WriteLine("-- {0} worker threads were injected", WorkerThreadReport.CreatedThreads);
        WorkerThreadReport.ShowThreads();
        WorkerThreadReport.ShutdownWorkerThreadReport();
    }
Beispiel #16
0
 private void Form1_FormClosing(object sender, FormClosingEventArgs e)
 {
     WorkerThreadReport.ShutdownWorkerThreadReport();
 }