线程池任务队列(五)

2014-11-24 10:13:24 · 作者: · 浏览: 2
ite FTasksCache;
property RecoverInterval:Integer read FRecoverInterval
write FRecoverInterval;
property IsAllowTheSameTask:Boolean read FIsAllowTheSameTask
write FIsAllowTheSameTask;
property Sorted:Boolean read FSorted write FSorted;
property TaskQueueCount:Integer read getTaskQueueCount;
property IdleQueueCount:Integer read getIdleQueueCount;
property BusyQueueCount:Integer read getBusyQueueCount;
property OnSortTask:TSortTaskQueueEvent read FOnSortTask write FOnSortTask;
property OnTaskWillDo:TTaskWillDoBeforeEvent read FOnTaskWillDo write FOnTaskWillDo;
property OnTaskFinished:TTaskFinishedEvent read FOnTaskFinished write FOnTaskFinished;
property OnTaskFull:TTaskQueueFullEvent read FOnTaskFull write FOnTaskFull;
property OnListenInfo:TListenCacheInfoEvent read FOnListenInfo write FOnListenInfo;
End;

implementation

{ TThreadPool }

constructor TThreadPool.Create;
var
tpError:Cardinal;
begin
Log:=TPoolLog.Create;
SetDefault;
CreateLock;

tpError := 0;

entTaskNotify:=Tevent.create(nil,false,false, 'TaskNotify');//事件信号
hTimeJump := CreateEvent(nil,False,False,'Timer');//自动回收心跳事件
if hTimeJump = 0 then
tpError := GetLastError;

//the same name of sign exists.
Case tpError of
ERROR_ALREADY_EXISTS:
begin
hTimeJump := 0;
Log.WriteLog('CreateTimerEvent Fail,the Same Name of Event Exists');
end;
End;
//预创建线程
CreateIdleThread(FMinNums);
Log.WriteLog('Thread Pool start run.',lInfo);
end;

destructor TThreadPool.Destroy;
begin
ClearQueue(IdleQueue);
ClearQueue(BusyQueue);
FreeLock;
if hTimeJump > 0 then
CloseHandle(hTimeJump);
entTaskNotify.Free;
Log.Free;
inherited;
Log.WriteLog('Thread Pool end run.',lInfo);
end;

procedure TThreadPool.DoTaskFull;
begin
if Assigned(FOnTaskFull) then
FOnTaskFull(self);
end;

procedure TThreadPool.SetDefault;
begin
FMinNums := PRE_NUM;
FMaxNums := MAX_NUM;
FTasksCache := MAX_TASKNUM;
FRecoverInterval := AUTO_FREE;
FIsAllowTheSameTask := False;
FAuto :=False;
FWaitFlag := True;
Waiting := nil;
FSorted := False;
end;

procedure TThreadPool.CreateLock;
begin
hIDleLock := TCriticalSection.Create;
hBusyLock := TCriticalSection.Create;
hTaskLock := TCriticalSection.Create;
end;

procedure TThreadPool.FreeLock;
begin
hIDleLock.Free;
hBusyLock.Free;
hTaskLock.Free;
end;

function TThreadPool.getBusyQueueCount: Integer;
begin
Result := QueueSize(BusyQueue);
end;

function TThreadPool.getIdleQueueCount: Integer;
begin
Result := QueueSize(IdleQueue);
end;

function TThreadPool.getTaskQueueCount: Integer;
begin
Result := TaskSzie(TaskQueue);
end;

procedure TThreadPool.CleanTasks;
begin
hTaskLock.Enter;
SetLength(TaskQueue,0);
hTaskLock.Leave;
end;

procedure TThreadPool.ListenPool;
begin
//正在执行任务的线程,空闲线程,队列中任务数
if Assigned(FOnListenInfo) t