近来在学习Eugene Agafonov编写的《C#多线程编程实战》(译),做些笔记也顺便分享一下^-^
using System;
using System.Threading;
using System.Diagnostics;
namespace 线程池与并行度
{
class Program
{
static void Main(string[] args)
{
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 threads: {0}", sw.ElapsedMilliseconds);
Console.ReadKey();
}
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.Write("{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.Write("{0},", Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(TimeSpan.FromSeconds(0.1));
countdown.Signal();
});
}
countdown.Wait();
Console.WriteLine();
}
}
}
}
当主程序启动时,创建了很多不同的线程,每个线程都运行一个操作。该操作打印出线程ID并阻塞线程100毫秒。结果我们创建了500个线程,全部并行运行这些操作。虽然在我的机器上总耗时是300毫秒,但所有的线程消耗了大量的操作系统资源。
然后我们使用了执行同样的任务,只不过将每个任务都加入到线程池中,在线程池中执行这些操作。线程池在快结束时创建了更多的线程,但仍然花费了更多的时间。我们为操作系统节省了内存和线程数,但是为此付出了更长的执行时间!