线程池
线程池
/// <author>cxg 2023-6-19</author> /// 异步任务队列调度 /// 每个线程都有自己的任务队列 /// 处理任务均衡算法:依次往每个线程的队列投递任务,线程从自己的队列中获取任务处理 unit tasks; interface uses Windows, Contnrs, SyncObjs, Classes, SysUtils; type TCallBack = procedure(task: Pointer) of object; type TThreadConf = class private fCallBack: TCallBack; fThreadNum: integer; threads: array of TThread; lock: TCriticalSection; procedure freeThreads; procedure newThreads; public constructor Create(const threadNum: integer = 0); destructor Destroy; override; public procedure startThreads; procedure stopThreads; procedure push(task: Pointer); public property onCallback: TCallBack read fCallBack write fCallBack; property threadNum: integer read fThreadNum; end; type TWorkThread = class(TThread) private fConf: TThreadConf; fQueue: TQueue; public constructor Create(conf: TThreadConf); destructor Destroy; override; public procedure Execute; override; procedure push(task: Pointer); end; implementation var gIndex: Integer = 0; { TThreadConf } procedure TThreadConf.push(task: Pointer); var i: Integer; begin lock.Enter; try i := gIndex mod fThreadNum; //轮循算法 inc(gIndex); finally lock.Leave; end; TWorkThread(threads[i]).push(task); end; constructor TThreadConf.Create(const threadNum: integer = 0); begin lock := TCriticalSection.Create; fThreadNum := threadNum; if fThreadNum = 0 then fThreadNum := cpucount; SetLength(threads, fThreadNum); newThreads; end; destructor TThreadConf.Destroy; begin freeThreads; FreeAndNil(lock); inherited; end; procedure TThreadConf.freeThreads; var thread: tthread; begin for thread in threads do begin thread.Terminate; thread.WaitFor; freeandnil(thread); end; end; procedure TThreadConf.newThreads; var i: Byte; begin for i := 0 to fThreadNum - 1 do threads[i] := TWorkThread.Create(Self); end; procedure TThreadConf.startThreads; var thread: tthread; begin for thread in threads do thread.Start; end; procedure TThreadConf.stopThreads; var thread: tthread; begin for thread in threads do thread.Suspend; end; { TWorkThread } constructor TWorkThread.Create(conf: TThreadConf); begin inherited Create(true); FreeOnTerminate := True; fConf := conf; fQueue := TQueue.Create; end; destructor TWorkThread.Destroy; begin FreeAndNil(fQueue); inherited; end; procedure TWorkThread.push(task: Pointer); begin fQueue.Push(task); end; procedure TWorkThread.Execute; var task: Pointer; begin while not Self.Terminated do begin task := fQueue.Pop; if task <> nil then if Assigned(fConf.fCallBack) then fConf.fCallBack(task); sleep(1); end; end; end.
本文来自博客园,作者:{咏南中间件},转载请注明原文链接:https://www.cnblogs.com/hnxxcxg/p/17488774.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
2022-06-18 引入OAS3和Swagger全面提升开发者体验
2017-06-18 咏南CS开发框架新的界面风格