线程池

`

using System.Collections.Concurrent;

namespace ConsoleApp1
{
internal class Program
{
static void Main(string[] args)
{
var rnd = new Random();

for (var i = 0; i < 1000; i++)
{
new Thread((state) =>
{
LazyThreadPool.QueueUserWorkItem((state) =>
{
try
{
Console.WriteLine($"Thread {Thread.CurrentThread.ManagedThreadId}, {state}");
Thread.Sleep(rnd.Next(5) * 1000);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}, "hello world:" + state);

Thread.Sleep(rnd.Next(500));
}).Start(i);
}

Console.ReadKey();
}
}

///


/// 线程池
///

public class LazyThreadPool
{
///
/// 最大线程数
///

private int _maxThreadCount;
///
/// 核心线程数
///

private int _coreThreadCount;
///
/// 工作线程
///

private List _threads = new List();
///
/// 任务队列
///

private BlockingCollection _queue = new BlockingCollection();

///


/// 默认线程池
///

private static LazyThreadPool _defaultPool;
///
/// 默认核心线程数
///

public static int DefaultCoreThreadCount { get; set; } = 2;

static LazyThreadPool()
{
_defaultPool = new LazyThreadPool(DefaultCoreThreadCount, Environment.ProcessorCount);
}

///


/// 向线程池添加任务
///

///
///
public static void QueueUserWorkItem(WaitCallback callback, object? state)
{
_defaultPool.QueueWorkItem(callback, state);
}

///


/// 构建线程池
///

///
///
public LazyThreadPool(int coreThreadCount, int maxThreadcount)
{
_coreThreadCount = coreThreadCount;
_maxThreadCount = maxThreadcount;

// 开启任务消费
this.StartConsuming();
}

///


/// 向线程池添加任务
///

///
///
public void QueueWorkItem(WaitCallback callback, object? state)
{
_queue.Add(new WorkItem(callback, state));
}

///


/// 开启任务消费
///

private void StartConsuming()
{
var thread = new Thread(() =>
{
foreach (var workItem in _queue.GetConsumingEnumerable())
{
// 查找闲置线程
var idleWorker = FindIdleWorker();

// 未找到,则等待(优化)
while (idleWorker == null)
{
idleWorker = FindIdleWorker();
Thread.Sleep(1);
}

// 分配任务
idleWorker.Assign(workItem.Callback, workItem.State);
}
});
thread.IsBackground = true;
thread.Start();
}

///


/// 查找空闲的线程
///

///
private WorkerThread? FindIdleWorker()
{
// 创建核心线程
if (_threads.Count == 0)
{
this.InitCoreWorkerThreads();
}

var idleWorker = _threads.FirstOrDefault(x => x.IsIdle);
if (idleWorker != null) return idleWorker;

if (_threads.Count < _maxThreadCount)
{
// 如果没有空闲线程,且线程池未满,则创建新线程
var worker = new WorkerThread();
_threads.Add(worker);
return worker;
}
else
{
// 如果没有空闲线程,且线程池已满,则返回null
return null;
}
}

///


/// 初始化核心线程
///

private void InitCoreWorkerThreads()
{
for (var i = 0; i < _coreThreadCount; i++)
{
var worker = new WorkerThread();
_threads.Add(worker);
}
}
}

///


/// 工作线程
///

public class WorkerThread
{
private Thread _thread;
private WaitCallback? _work = null;
private object? _workState = null;
private AutoResetEvent _autoResetEvent = new AutoResetEvent(false);

public WorkerThread()
{
this._thread = new Thread((state) =>
{
var worker = (state as WorkerThread)!;

while (true)
{
// 未分配任务时,等待
_autoResetEvent.WaitOne();

if (!worker.IsIdle)
{
worker.ExecWork();
worker.SetIdle();
}
}
});
this._thread.IsBackground = true;
this._thread.Start(this);
}

///


/// 为工作线程分配任务
///

///
///
public void Assign(WaitCallback callback, object? state)
{
this._work = callback;
this._workState = state;
_autoResetEvent.Set();
}

///


/// 是否空闲
///

public bool IsIdle
{
get
{
return this._work == null;
}
}

///


/// 执行工作
///

private void ExecWork()
{
if (this._work != null) this._work(this._workState);
}

///


/// 设置为限制状态
///

private void SetIdle()
{
this._work = null;
}
}

///


/// 任务项
///

///
///
public record WorkItem(WaitCallback Callback, object? State);
}

`

posted @ 2024-08-20 10:06  pojianbing  阅读(34)  评论(0)    收藏  举报