扩展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;