扩展Delphi的线程同步对象(1)

王朝delphi·作者佚名  2006-01-08
窄屏简体版  字體: |||超大  

扩展Delphi的线程同步对象(1)

[ 作者: 于华 添加时间: 2001-5-5 18:01:08 ]

来源:www.ccidnet.com

在编写多线程应用程序时,最重要的是控制好线程间的同步资源访问,以保证线程的安全运行。Win 32 API提供了一组同步对象,如:信号灯(Semaphore)、互斥(Mutex)、临界区(CriticalSection)和事件(Event)等,用来解决这个问题。

Delphi分别将事件对象和临界区对象封装为Tevent对象和TcritialSection对象,使得这两个对象的使用简单且方便。但是如果在Delphi程序中要使用信号灯或互斥等对象就必须借助于复杂的Win32 API函数,这对那些不熟悉Win32 API函数的编程人员来说很不方便。因此,笔者用Delphi构造了两个类,对信号灯和互斥对象进行了封装(分别为TSemaphore和TMutex),希望对广大Delphi编程人员有所帮助。

一、类的构造

我们先对Win32 API的信号灯对象和互斥对象进行抽象,构造一个父类THandleObjectEx,然后由这个父类派生出两个子类Tsemphore和Tmutex。

类的源代码如下:

unit SyncobjsEx;

interface

uses Windows,Messages,SysUtils,Classes,Syncobjs;

type

THandleObjectEx = class(THandleObject)

// THandleObjectEx为互斥类和信号灯类的父类

protected

FHandle: THandle;

FLastError: Integer;

public

destructor Destroy; override;

procedure Release;override;

function WaitFor(Timeout: DWORD): TWaitResult;

property LastError:Integer read FLastError;

property Handle: THandle read FHandle;

end;

TMutex = class(THandleObjectEx)//互斥类

public

constructor Create(MutexAttributes: PSecurityAttributes; InitialOwner: Boolean;const Name:string);

procedure Release; override;

end;

TSemaphore = class(THandleObjectEx)

//信号灯类

public

constructor Create(SemaphoreAttributes: PSecurityAttributes;InitialCount:Integer;MaximumCount: integer; const Name: string);

procedure Release(ReleaseCount: Integer=1;PreviousCount:Pointer=nil);overload;

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有  導航