线程池与并行度

本节将展示线程池如何工作于大量的异步操作,以及它与创建大量单独的线程的方式有和不同。

代码Demo:

using System;
using System.Threading;
using System.Diagnostics;

在Main方法下面加入以下代码片段:

static void UseThreads(int numberOfOperations)
{
using (var countdown = new CountdownEvent(numberOfOperations))
{
Console.WriteLine("Scheduling work by creating threads");
for (int i = 0; i < numberOfOperations; i++)
{
var thread = new Thread(() =>
{
Console.WriteLine("{0},", Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(TimeSpan.FromSeconds(0.1));
countdown.Signal();
});
thread.Start();
}
countdown.Wait();
Console.WriteLine();
}
}
static void UseThreadPool(int numberOfOperations)
{
using (var countdown = new CountdownEvent(numberOfOperations))
{
Console.WriteLine("Starting work on a threadpool");
for (int i = 0; i < numberOfOperations; i++)
{
ThreadPool.QueueUserWorkItem(_ =>
{
Console.WriteLine("{0},", Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(TimeSpan.FromSeconds(0.1));
countdown.Signal();
});
}
countdown.Wait();
Console.WriteLine();
}
}

在Main方法中加入以下代码片段:

const int numberOfOperations = 500;
var sw = new Stopwatch();
sw.Start();
UseThreads(numberOfOperations);
sw.Stop();
Console.WriteLine("Execution time using threads:{0}", sw.ElapsedMilliseconds);
sw.Reset();
sw.Start();

UseThreadPool(numberOfOperations);
sw.Stop();
Console.WriteLine("Execution time using threadpool:{0}", sw.ElapsedMilliseconds);

工作原理:

当主程序启动时,创建了很多不同的线程,每个线程都运行一个操作。该操作打印出线程ID并阻塞线程100毫秒。结果我们创建了500个线程,全部并行运行这些操作。虽然在我的机器上的总耗时是300毫秒,但是所有线程消耗了大量的操作系统资源。

然后我们使用了执行同样的任务,只不过部位每个操作创建一个线程,儿将他们放入到线程池中。然后线程池开始执行这些操作。线程池在快结束时创建更多的线程,但是仍然花费了更多的时间,在我机器上是12秒。我们为操作系统节省了内存和线程数,但是为此付出了更长的执行时间。

猜你喜欢

转载自www.cnblogs.com/v-haoz/p/9270258.html