• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

delphi线程使用

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
unit untWorkThread;

interface

uses
  Windows,Classes,SysUtils;

type
  TWorkItem=class
  end;
  TProcessWork=procedure (Sender:TObject;Work:TWorkItem) of Object;
  TWorkThread=class(TThread)
  private
    FCriticalSection:TRTLCriticalSection;
    hEvent:Cardinal;
    FList:TList;
    FProcessWork:TProcessWork;
    procedure ProcessWork(Work:TWorkItem);
    function GetWork(var AWork:TWorkItem):Boolean;
  protected
    procedure Execute;override;
  public
    procedure AddWork(AWork:TWorkItem);
    constructor Create;
    destructor Destroy; override;
    property OnProcessWork:TProcessWork read FProcessWork write FProcessWork;
  end;

implementation

{TWorkThread}

constructor TWorkThread.Create;
begin
  InitializeCriticalSection(FCriticalSection);
  hEvent:=CreateEvent(nil,False,False,nil);
  FList:=TList.Create;
  Self.FreeOnTerminate:=False;
  inherited Create(False);
end;

destructor TWorkThread.Destroy;
var
  i:Integer;
begin
  for i:=FList.Count-1 downto 0 do TWorkItem(FList.Items[i]).Free;
  DeleteCriticalSection(FCriticalSection);
  FList.Free;
  CloseHandle(hEvent);
end;

function TWorkThread.GetWork(var AWork:TWorkItem):Boolean;
begin
  Result:=False;
  EnterCriticalSection(FCriticalSection);
  try
    if FList.Count>0 then
    begin
      AWork:=TWorkItem(FList.Items[0]);
      FList.Delete(0);
      Result:=True;
    end;
  finally
    LeaveCriticalSection(FCriticalSection);
  end;
end;

procedure TWorkThread.Execute;
var
  Work:TWorkItem;
begin
  while not Self.Terminated do
  begin
    WaitForSingleObject(hEvent,INFINITE);
    while GetWork(Work) do
    begin
      ProcessWork(Work);
      Work.Free;
    end;
  end;
end;

procedure TWorkThread.ProcessWork(Work:TWorkItem);
begin
  if Assigned(FProcessWork) then FProcessWork(Self,Work);
end;

procedure TWorkThread.AddWork(AWork:TWorkItem);
begin
  EnterCriticalSection(FCriticalSection);
  try
    FList.Add(AWork);
  finally
    LeaveCriticalSection(FCriticalSection);
  end;
  SetEvent(hEvent);
end;

end.

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
matlab中imfilter、conv2、imfilter2用法及区别发布时间:2022-07-18
下一篇:
利用Matlab求解Laplace方程发布时间:2022-07-18
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap