DELPHI 线程类


======================================================
注:本文源代码点此下载
======================================================

delphi中有一个线程类tthread是用来实现多线程编程的,这个绝大多数delphi书藉都有说到,但基本上都是对tthread类的几个成员作一简单介绍,再说明一下execute的实现和synchronize的用法就完了。然而这并不是多线程编程的全部,我写此文的目的在于对此作一个补充。

线程本质上是进程中一段并发运行的代码。一个进程至少有一个线程,即所谓的主线程。同时还可以有多个子线程。当一个进程中用到超过一个线程时,就是所谓的“多线程”。

那么这个所谓的“一段代码”是如何定义的呢?其实就是一个函数或过程(对delphi而言)。

如果用windows api来创建线程的话,是通过一个叫做createthread的api函数来实现的,它的定义为:

handle createthread(

lpsecurity_attributes lpthreadattributes,

dword dwstacksize,

lpthread_start_routine lpstartaddress,

lpvoid lpparameter,

dword dwcreationflags,

lpdword lpthreadid

);

其各参数如它们的名称所说,分别是:线程属性(用于在nt下进行线程的安全属性设置,在9x下无效),堆栈大小,起始地址,参数,创建标志(用于设置线程创建时的状态),线程id,最后返回线程handle。其中的起始地址就是线程函数的入口,直至线程函数结束,线程也就结束了。

整个线程的执行过程如下图所示:

因为createthread参数很多,而且是windows的api,所以在c runtime library里提供了一个通用的线程函数(理论上可以在任何支持线程的os中使用):

unsigned long _beginthread(void (_userentry *__start)(void *), unsigned __stksize, void *__arg);

delphi也提供了一个相同功能的类似函数:

function beginthread(securityattributes: pointer; stacksize: longword; threadfunc: tthreadfunc; parameter: pointer; creationflags: longword; var threadid: longword): integer;

这三个函数的功能是基本相同的,它们都是将线程函数中的代码放到一个独立的线程中执行。线程函数与一般函数的最大不同在于,线程函数一启动,这三个线程启动函数就返回了,主线程继续向下执行,而线程函数在一个独立的线程中执行,它要执行多久,什么时候返回,主线程是不管也不知道的。

正常情况下,线程函数返回后,线程就终止了。但也有其它方式:

windows api:

void exitthread( dword dwexitcode );

c runtime library:

void _endthread(void);

delphi runtime library:

procedure endthread(exitcode: integer);

为了记录一些必要的线程数据(状态/属性等),os会为线程创建一个内部object,如在windows中那个handle便是这个内部object的handle,所以在线程结束的时候还应该释放这个object。

虽然说用api或rtl(runtime library)已经可以很方便地进行多线程编程了,但是还是需要进行较多的细节处理,为此delphi在classes单元中对线程作了一个较好的封装,这就是vcl的线程类:tthread

使用这个类也很简单,大多数的delphi书籍都有说,基本用法是:先从tthread派生一个自己的线程类(因为tthread是一个抽象类,不能生成实例),然后是override抽象方法:execute(这就是线程函数,也就是在线程中执行的代码部分),如果需要用到可视vcl对象,还需要通过synchronize过程进行。关于之方面的具体细节,这里不再赘述,请参考相关书籍。

本文接下来要讨论的是tthread类是如何对线程进行封装的,也就是深入研究一下tthread类的实现。因为只是真正地了解了它,才更好地使用它。

下面是delphi7中tthread类的声明(本文只讨论在windows平台下的实现,所以去掉了所有有关linux平台部分的代码):

tthread = class

private

fhandle: thandle;

fthreadid: thandle;

fcreatesuspended: boolean;

fterminated: boolean;

fsuspended: boolean;

ffreeonterminate: boolean;

ffinished: boolean;

freturnvalue: integer;

fonterminate: tnotifyevent;

fsynchronize: tsynchronizerecord;

ffatalexception: tobject;

procedure callonterminate;

class procedure synchronize(asyncrec: psynchronizerecord); overload;

function getpriority: tthreadpriority;

procedure setpriority(value: tthreadpriority);

procedure setsuspended(value: boolean);

protected

procedure checkthreaderror(errcode: integer); overload;

procedure checkthreaderror(success: boolean); overload;

procedure doterminate; virtual;

procedure execute; virtual; abstract;

procedure synchronize(method: tthreadmethod); overload;

property returnvalue: integer read freturnvalue write freturnvalue;

property terminated: boolean read fterminated;

public

constructor create(createsuspended: boolean);

destructor destroy; override;

procedure afterconstruction; override;

procedure resume;

procedure suspend;

procedure terminate;

function waitfor: longword;

class procedure synchronize(athread: tthread; amethod: tthreadmethod); overload;

class procedure staticsynchronize(athread: tthread; amethod: tthreadmethod);

property fatalexception: tobject read ffatalexception;

property freeonterminate: boolean read ffreeonterminate write ffreeonterminate;

property handle: thandle read fhandle;

property priority: tthreadpriority read getpriority write setpriority;

property suspended: boolean read fsuspended write setsuspended;

property threadid: thandle read fthreadid;

property onterminate: tnotifyevent read fonterminate write fonterminate;

end;

tthread类在delphi的rtl里算是比较简单的类,类成员也不多,类属性都很简单明白,本文将只对几个比较重要的类成员方法和唯一的事件:onterminate作详细分析。

首先就是构造函数:

constructor tthread.create(createsuspended: boolean);

begin

inherited create;

addthread;

fsuspended := createsuspended;

fcreatesuspended := createsuspended;

fhandle := beginthread(nil, 0, @threadproc, pointer(self), create_suspended, fthreadid);

if fhandle = 0 then

raise ethread.createresfmt(@sthreadcreateerror, [syserrormessage(getlasterror)]);

end;

虽然这个构造函数没有多少代码,但却可以算是最重要的一个成员,因为线程就是在这里被创建的。

在通过inherited调用tobject.create后,第一句就是调用一个过程:addthread,其源码如下:

procedure addthread;

begin

interlockedincrement(threadcount);

end;

同样有一个对应的removethread:

procedure removethread;

begin

interlockeddecrement(threadcount);

end;

它们的功能很简单,就是通过增减一个全局变量来统计进程中的线程数。只是这里用于增减变量的并不是常用的inc/dec过程,而是用了interlockedincrement/interlockeddecrement这一对过程,它们实现的功能完全一样,都是对变量加一或减一。但它们有一个最大的区别,那就是interlockedincrement/interlockeddecrement是线程安全的。即它们在多线程下能保证执行结果正确,而inc/dec不能。或者按操作系统理论中的术语来说,这是一对“原语”操作。

以加一为例来说明二者实现细节上的不同:

一般来说,对内存数据加一的操作分解以后有三个步骤:

1、从内存中读出数据

2、数据加一

3、存入内存

现在假设在一个两个线程的应用中用inc进行加一操作可能出现的一种情况:

1、线程a从内存中读出数据(假设为3)

2、线程b从内存中读出数据(也是3)

3、线程a对数据加一(现在是4)

4、线程b对数据加一(现在也是4)

5、线程a将数据存入内存(现在内存中的数据是4)

6、线程b也将数据存入内存(现在内存中的数据还是4,但两个线程都对它加了一,应该是5才对,所以这里出现了错误的结果)

而用interlockincrement过程则没有这个问题,因为所谓“原语”是一种不可中断的操作,即操作系统能保证在一个“原语”执行完毕前不会进行线程切换。所以在上面那个例子中,只有当线程a执行完将数据存入内存后,线程b才可以开始从中取数并进行加一操作,这样就保证了即使是在多线程情况下,结果也一定会是正确的。

前面那个例子也说明一种“线程访问冲突”的情况,这也就是为什么线程之间需要“同步”(synchronize),关于这个,在后面说到同步时还会再详细讨论。

说到同步,有一个题外话:加拿大滑铁卢大学的教授李明曾就synchronize一词在“线程同步”中被译作“同步”提出过异议,个人认为他说的其实很有道理。在中文中“同步”的意思是“同时发生”,而“线程同步”目的就是避免这种“同时发生”的事情。而在英文中,synchronize的意思有两个:一个是传统意义上的同步(to occur at the same time),另一个是“协调一致”(to operate in unison)。在“线程同步”中的synchronize一词应该是指后面一种意思,即“保证多个线程在访问同一数据时,保持协调一致,避免出错”。不过像这样译得不准的词在it业还有很多,既然已经是约定俗成了,本文也将继续沿用,只是在这里说明一下,因为软件开发是一项细致的工作,该弄清楚的,绝不能含糊。

扯远了,回到tthread的构造函数上,接下来最重要就是这句了:

fhandle := beginthread(nil, 0, @threadproc, pointer(self), create_suspended, fthreadid);

这里就用到了前面说到的delphi rtl函数beginthread,它有很多参数,关键的是第三、四两个参数。第三个参数就是前面说到的线程函数,即在线程中执行的代码部分。第四个参数则是传递给线程函数的参数,在这里就是创建的线程对象(即self)。其它的参数中,第五个是用于设置线程在创建后即挂起,不立即执行(启动线程的工作是在afterconstruction中根据createsuspended标志来决定的),第六个是返回线程id。

现在来看tthread的核心:线程函数threadproc。有意思的是这个线程类的核心却不是线程的成员,而是一个全局函数(因为beginthread过程的参数约定只能用全局函数)。下面是它的代码:

function threadproc(thread: tthread): integer;

var

freethread: boolean;

begin

try

if not thread.terminated then

try

thread.execute;

except

thread.ffatalexception := acquireexceptionobject;

end;

finally

freethread := thread.ffreeonterminate;

result := thread.freturnvalue;

thread.doterminate;

thread.ffinished := true;

signalsyncevent;

if freethread then thread.free;

endthread(result);

end;

end;

虽然也没有多少代码,但却是整个tthread中最重要的部分,因为这段代码是真正在线程中执行的代码。下面对代码作逐行说明:

首先判断线程类的terminated标志,如果未被标志为终止,则调用线程类的execute方法执行线程代码,因为tthread是抽象类,execute方法是抽象方法,所以本质上是执行派生类中的execute代码。

所以说,execute就是线程类中的线程函数,所有在execute中的代码都需要当作线程代码来考虑,如防止访问冲突等。

如果execute发生异常,则通过acquireexceptionobject取得异常对象,并存入线程类的ffatalexception成员中。

最后是线程结束前做的一些收尾工作。局部变量freethread记录了线程类的freeonterminated属性的设置,然后将线程返回值设置为线程类的返回值属性的值。然后执行线程类的doterminate方法。

doterminate方法的代码如下:

procedure tthread.doterminate;

begin

if assigned(fonterminate) then synchronize(callonterminate);

end;

很简单,就是通过synchronize来调用callonterminate方法,而callonterminate方法的代码如下,就是简单地调用onterminate事件:

procedure tthread.callonterminate;

begin

if assigned(fonterminate) then fonterminate(self);

end;

因为onterminate事件是在synchronize中执行的,所以本质上它并不是线程代码,而是主线程代码(具体见后面对synchronize的分析)。

执行完onterminate后,将线程类的ffinished标志设置为true。

接下来执行signalsyncevent过程,其代码如下:

procedure signalsyncevent;

begin

setevent(syncevent);

end;

也很简单,就是设置一下一个全局event:syncevent,关于event的使用,本文将在后文详述,而syncevent的用途将在waitfor过程中说明。

然后根据freethread中保存的freeonterminate设置决定是否释放线程类,在线程类释放时,还有一些些操作,详见接下来的析构函数实现。

最后调用endthread结束线程,返回线程返回值。

至此,线程完全结束。

说完构造函数,再来看析构函数:

destructor tthread.destroy;

begin

if (fthreadid0 then closehandle(fhandle);

inherited destroy;

ffatalexception.free;

removethread;

end;

在线程对象被释放前,首先要检查线程是否还在执行中,如果线程还在执行中(线程id不为0,并且线程结束标志未设置),则调用terminate过程结束线程。terminate过程只是简单地设置线程类的terminated标志,如下面的代码:

procedure tthread.terminate;

begin

fterminated := true;

end;

所以线程仍然必须继续执行到正常结束后才行,而不是立即终止线程,这一点要注意。

在这里说一点题外话:很多人都问过我,如何才能“立即”终止线程(当然是指用tthread创建的线程)。结果当然是不行!终止线程的唯一办法就是让execute方法执行完毕,所以一般来说,要让你的线程能够尽快终止,必须在execute方法中在较短的时间内不断地检查terminated标志,以便能及时地退出。这是设计线程代码的一个很重要的原则!

当然如果你一定要能“立即”退出线程,那么tthread类不是一个好的选择,因为如果用api强制终止线程的话,最终会导致tthread线程对象不能被正确释放,在对象析构时出现access violation。这种情况你只能用api或rtl函数来创建线程。

如果线程处于启动挂起状态,则将线程转入运行状态,然后调用waitfor进行等待,其功能就是等待到线程结束后才继续向下执行。关于waitfor的实现,将放到后面说明。

线程结束后,关闭线程handle(正常线程创建的情况下handle都是存在的),释放操作系统创建的线程对象。

然后调用tobject.destroy释放本对象,并释放已经捕获的异常对象,最后调用removethread减小进程的线程数。

其它关于suspend/resume及线程优先级设置等方面,不是本文的重点,不再赘述。下面要讨论的是本文的另两个重点:synchronize和waitfor。

但是在介绍这两个函数之前,需要先介绍另外两个线程同步技术:事件和临界区。

事件(event)与delphi中的事件有所不同。从本质上说,event其实相当于一个全局的布尔变量。它有两个赋值操作:set和reset,相当于把它设置为true或false。而检查它的值是通过waitfor操作进行。对应在windows平台上,是三个api函数:setevent、resetevent、waitforsingleobject(实现waitfor功能的api还有几个,这是最简单的一个)。

这三个都是原语,所以event可以实现一般布尔变量不能实现的在多线程中的应用。set和reset的功能前面已经说过了,现在来说一下waitfor的功能:

waitfor的功能是检查event的状态是否是set状态(相当于true),如果是则立即返回,如果不是,则等待它变为set状态,在等待期间,调用waitfor的线程处于挂起状态。另外waitfor有一个参数用于超时设置,如果此参数为0,则不等待,立即返回event的状态,如果是infinite则无限等待,直到set状态发生,若是一个有限的数值,则等待相应的毫秒数后返回event的状态。

当event从reset状态向set状态转换时,唤醒其它由于waitfor这个event而挂起的线程,这就是它为什么叫event的原因。所谓“事件”就是指“状态的转换”。通过event可以在线程间传递这种“状态转换”信息。

当然用一个受保护(见下面的临界区介绍)的布尔变量也能实现类似的功能,只要用一个循环检查此布尔值的代码来代替waitfor即可。从功能上说完全没有问题,但实际使用中就会发现,这样的等待会占用大量的cpu资源,降低系统性能,影响到别的线程的执行速度,所以是不经济的,有的时候甚至可能会有问题。所以不建议这样用。

临界区(criticalsection)则是一项共享数据访问保护的技术。它其实也是相当于一个全局的布尔变量。但对它的操作有所不同,它只有两个操作:enter和leave,同样可以把它的两个状态当作true和false,分别表示现在是否处于临界区中。这两个操作也是原语,所以它可以用于在多线程应用中保护共享数据,防止访问冲突。

用临界区保护共享数据的方法很简单:在每次要访问共享数据之前调用enter设置进入临界区标志,然后再操作数据,最后调用leave离开临界区。它的保护原理是这样的:当一个线程进入临界区后,如果此时另一个线程也要访问这个数据,则它会在调用enter时,发现已经有线程进入临界区,然后此线程就会被挂起,等待当前在临界区的线程调用leave离开临界区,当另一个线程完成操作,调用leave离开后,此线程就会被唤醒,并设置临界区标志,开始操作数据,这样就防止了访问冲突。

以前面那个interlockedincrement为例,我们用criticalsection(windows api)来实现它:

var

interlockedcrit : trtlcriticalsection;

procedure interlockedincrement( var avalue : integer );

begin

entercriticalsection( interlockedcrit );

inc( avalue );

leavecriticalsection( interlockedcrit );

end;

现在再来看前面那个例子:

1.线程a进入临界区(假设数据为3)

2.线程b进入临界区,因为a已经在临界区中,所以b被挂起

3.线程a对数据加一(现在是4)

4.线程a离开临界区,唤醒线程b(现在内存中的数据是4)

5.线程b被唤醒,对数据加一(现在就是5了)

6.线程b离开临界区,现在的数据就是正确的了。

临界区就是这样保护共享数据的访问。

关于临界区的使用,有一点要注意:即数据访问时的异常情况处理。因为如果在数据操作时发生异常,将导致leave操作没有被执行,结果将使本应被唤醒的线程未被唤醒,可能造成程序的没有响应。所以一般来说,如下面这样使用临界区才是正确的做法:

entercriticalsection

try

//操作临界区数据

finally

leavecriticalsection

end;

最后要说明的是,event和criticalsection都是操作系统资源,使用前都需要创建,使用完后也同样需要释放。如tthread类用到的一个全局event:syncevent和全局criticalsection:theadlock,都是在initthreadsynchronization和donethreadsynchronization中进行创建和释放的,而它们则是在classes单元的initialization和finalization中被调用的。

由于在tthread中都是用api来操作event和criticalsection的,所以前面都是以api为例,其实delphi已经提供了对它们的封装,在syncobjs单元中,分别是tevent类和tcriticalsection类。用法也与前面用api的方法相差无几。因为tevent的构造函数参数过多,为了简单起见,delphi还提供了一个用默认参数初始化的event类:tsimpleevent。

顺便再介绍一下另一个用于线程同步的类:tmultireadexclusivewritesynchronizer,它是在sysutils单元中定义的。据我所知,这是delphi rtl中定义的最长的一个类名,还好它有一个短的别名:tmrewsync。至于它的用处,我想光看名字就可以知道了,我也就不多说了。

有了前面对event和criticalsection的准备知识,可以正式开始讨论synchronize和waitfor了。

我们知道,synchronize是通过将部分代码放到主线程中执行来实现线程同步的,因为在一个进程中,只有一个主线程。先来看看synchronize的实现:

procedure tthread.synchronize(method: tthreadmethod);

begin

fsynchronize.fthread := self;

fsynchronize.fsynchronizeexception := nil;

fsynchronize.fmethod := method;

synchronize(@fsynchronize);

end;

其中fsynchronize是一个记录类型:

psynchronizerecord = ^tsynchronizerecord;

tsynchronizerecord = record

fthread: tobject;

fmethod: tthreadmethod;

fsynchronizeexception: tobject;

end;

用于进行线程和主线程之间进行数据交换,包括传入线程类对象,同步方法及发生的异常。

在synchronize中调用了它的一个重载版本,而且这个重载版本比较特别,它是一个“类方法”。所谓类方法,是一种特殊的类成员方法,它的调用并不需要创建类实例,而是像构造函数那样,通过类名调用。之所以会用类方法来实现它,是因为为了可以在线程对象没有创建时也能调用它。不过实际中是用它的另一个重载版本(也是类方法)和另一个类方法staticsynchronize。下面是这个synchronize的代码:

class procedure tthread.synchronize(asyncrec: psynchronizerecord);

var

syncproc: tsyncproc;

begin

if getcurrentthreadid = mainthreadid then

asyncrec.fmethod

else

begin

syncproc.signal := createevent(nil, true, false, nil);

try

entercriticalsection(threadlock);

try

if synclist = nil then

synclist := tlist.create;

syncproc.syncrec := asyncrec;

synclist.add(@syncproc);

signalsyncevent;

if assigned(wakemainthread) then

wakemainthread(syncproc.syncrec.fthread);

leavecriticalsection(threadlock);

try

waitforsingleobject(syncproc.signal, infinite);

finally

entercriticalsection(threadlock);

end;

finally

leavecriticalsection(threadlock);

end;

finally

closehandle(syncproc.signal);

end;

if assigned(asyncrec.fsynchronizeexception) then raise asyncrec.fsynchronizeexception;

end;

end;

这段代码略多一些,不过也不算太复杂。

首先是判断当前线程是否是主线程,如果是,则简单地执行同步方法后返回。

如果不是主线程,则准备开始同步过程。

通过局部变量syncproc记录线程交换数据(参数)和一个event handle,其记录结构如下:

tsyncproc = record

syncrec: psynchronizerecord;

signal: thandle;

end;

然后创建一个event,接着进入临界区(通过全局变量threadlock进行,因为同时只能有一个线程进入synchronize状态,所以可以用全局变量记录),然后就是把这个记录数据存入synclist这个列表中(如果这个列表不存在的话,则创建它)。可见threadlock这个临界区就是为了保护对synclist的访问,这一点在后面介绍checksynchronize时会再次看到。

再接下就是调用signalsyncevent,其代码在前面介绍tthread的构造函数时已经介绍过了,它的功能就是简单地将syncevent作一个set的操作。关于这个syncevent的用途,将在后面介绍waitfor时再详述。

接下来就是最主要的部分了:调用wakemainthread事件进行同步操作。wakemainthread是一个tnotifyevent类型的全局事件。这里之所以要用事件进行处理,是因为synchronize方法本质上是通过消息,将需要同步的过程放到主线程中执行,如果在一些没有消息循环的应用中(如console或dll)是无法使用的,所以要使用这个事件进行处理。

而响应这个事件的是application对象,下面两个方法分别用于设置和清空wakemainthread事件的响应(来自forms单元):

procedure tapplication.hooksynchronizewakeup;

begin

classes.wakemainthread := wakemainthread;

end;

procedure tapplication.unhooksynchronizewakeup;

begin

classes.wakemainthread := nil;

end;

上面两个方法分别是在tapplication类的构造函数和析构函数中被调用。

这就是在application对象中wakemainthread事件响应的代码,消息就是在这里被发出的,它利用了一个空消息来实现:

procedure tapplication.wakemainthread(sender: tobject);

begin

postmessage(handle, wm_null, 0, 0);

end;

而这个消息的响应也是在application对象中,见下面的代码(删除无关的部分):

procedure tapplication.wndproc(var message: tmessage);

begin

try

with message do

case msg of

wm_null:

checksynchronize;

except

handleexception(self);

end;

end;

其中的checksynchronize也是定义在classes单元中的,由于它比较复杂,暂时不详细说明,只要知道它是具体处理synchronize功能的部分就好,现在继续分析synchronize的代码。

在执行完wakemainthread事件后,就退出临界区,然后调用waitforsingleobject开始等待在进入临界区前创建的那个event。这个event的功能是等待这个同步方法的执行结束,关于这点,在后面分析checksynchronize时会再说明。

注意在waitforsingleobject之后又重新进入临界区,但没有做任何事就退出了,似乎没有意义,但这是必须的!

因为临界区的enter和leave必须严格的一一对应。那么是否可以改成这样呢:

if assigned(wakemainthread) then

wakemainthread(syncproc.syncrec.fthread);

waitforsingleobject(syncproc.signal, infinite);

finally

leavecriticalsection(threadlock);

end;

上面的代码和原来的代码最大的区别在于把waitforsingleobject也纳入临界区的限制中了。看上去没什么影响,还使代码大大简化了,但真的可以吗?

事实上是不行!

因为我们知道,在enter临界区后,如果别的线程要再进入,则会被挂起。而waitfor方法则会挂起当前线程,直到等待别的线程setevent后才会被唤醒。如果改成上面那样的代码的话,如果那个setevent的线程也需要进入临界区的话,死锁(deadlock)就发生了(关于死锁的理论,请自行参考操作系统原理方面的资料)。

死锁是线程同步中最需要注意的方面之一!

最后释放开始时创建的event,如果被同步的方法返回异常的话,还会在这里再次抛出异常。

回到前面checksynchronize,见下面的代码:

function checksynchronize(timeout: integer = 0): boolean;

var

syncproc: psyncproc;

localsynclist: tlist;

begin

if getcurrentthreadid0 then

waitforsyncevent(timeout)

else

resetsyncevent;

localsynclist := nil;

entercriticalsection(threadlock);

try

integer(localsynclist) := interlockedexchange(integer(synclist), integer(localsynclist));

try

result := (localsynclist0);

if result then

begin

while localsynclist.count > 0 do

begin

syncproc := localsynclist[0];

localsynclist.delete(0);

leavecriticalsection(threadlock);

try

try

syncproc.syncrec.fmethod;

except

syncproc.syncrec.fsynchronizeexception := acquireexceptionobject;

end;

finally

entercriticalsection(threadlock);

end;

setevent(syncproc.signal);

end;

end;

finally

localsynclist.free;

end;

finally

leavecriticalsection(threadlock);

end;

end;

首先,这个方法必须在主线程中被调用(如前面通过消息传递到主线程),否则就抛出异常。

接下来调用resetsyncevent(它与前面setsyncevent对应的,之所以不考虑waitforsyncevent的情况,是因为只有在linux版下才会调用带参数的checksynchronize,windows版下都是调用默认参数0的checksynchronize)。

现在可以看出synclist的用途了:它是用于记录所有未被执行的同步方法的。因为主线程只有一个,而子线程可能有很多个,当多个子线程同时调用同步方法时,主线程可能一时无法处理,所以需要一个列表来记录它们。

在这里用一个局部变量localsynclist来交换synclist,这里用的也是一个原语:interlockedexchange。同样,这里也是用临界区将对synclist的访问保护起来。

只要localsynclist不为空,则通过一个循环来依次处理累积的所有同步方法调用。最后把处理完的localsynclist释放掉,退出临界区。

再来看对同步方法的处理:首先是从列表中移出(取出并从列表中删除)第一个同步方法调用数据。然后退出临界区(原因当然也是为了防止死锁)。

接着就是真正的调用同步方法了。

如果同步方法中出现异常,将被捕获后存入同步方法数据记录中。

重新进入临界区后,调用setevent通知调用线程,同步方法执行完成了(详见前面synchronize中的waitforsingleobject调用)。

至此,整个synchronize的实现介绍完成。

最后来说一下waitfor,它的功能就是等待线程执行结束。其代码如下:

function tthread.waitfor: longword;

var

h: array[0..1] of thandle;

waitresult: cardinal;

msg: tmsg;

begin

h[0] := fhandle;

if getcurrentthreadid = mainthreadid then

begin

waitresult := 0;

h[1] := syncevent;

repeat

{ this prevents a potential deadlock if the background thread

does a sendmessage to the foreground thread }

if waitresult = wait_object_0 + 2 then

peekmessage(msg, 0, 0, 0, pm_noremove);

waitresult := msgwaitformultipleobjects(2, h, false, 1000, qs_sendmessage);

checkthreaderror(waitresult'' then

fwinname := threadname

else

fwinname := 'thread window';

{$else}

feventlist := tlist.create;

initializecriticalsection(fctlsect);

{$endif}

fwaithandle := createevent(nil, true, false, nil);

fdoloop := loop;//default disable thread loop

inherited create(false);//create thread

freeonterminate := true;//thread quit and free object

//call resume method in constructor method

resume;

//wait until thread message loop started

waitforsingleobject(fwaithandle,infinite);

end;

{------------------------------------------------------------------------------}

procedure tmsgthread.afterconstruction;

begin

end;

{------------------------------------------------------------------------------}

destructor tmsgthread.destroy;

begin

{$ifdef use_window_message}

{$else}

feventlist.free;

deletecriticalsection(fctlsect);

{$endif}

inherited;

end;

{//}

procedure tmsgthread.execute;

var

mret:boolean;

aret:boolean;

{$ifndef use_window_message}

umsg:tmessage;

{$endif}

begin

{$ifdef use_window_message}

fmsgwin := createwindow('static',pchar(fwinname),ws_popup,0,0,0,0,0,0,hinstance,nil);

setwindowlong(fmsgwin, gwl_wndproc, longint(makeobjectinstance(msgwinproc)));

{$else}

peekmessage(msg,0,wm_user,wm_user,pm_noremove); //force system alloc a msgqueue

{$endif}

//notify conctructor can returen.

setevent(fwaithandle);

closehandle(fwaithandle);

mret := true;

try

doinit;

while mret do//message loop

begin

if fdoloop then

begin

aret := peekmessage(msg,0,0,0,pm_remove);

if aret and (msg.message0 then

begin

aevent := feventlist.items[0];

if aeventwm_quit then

begin

{$ifdef use_window_message}

translatemessage(msg);

dispatchmessage(msg);

{$else}

umsg.msg := msg.message;

umsg.wparam := msg.wparam;

umsg.lparam := msg.lparam;

doprocessmsg(umsg);

{$endif}

end;

end;

{//}

procedure tmsgthread.doinit;

begin

end;

procedure tmsgthread.douninit;

begin

end;

procedure tmsgthread.domsgloop;

begin

sleep(1);

end;

{//}

procedure tmsgthread.quitthread;

begin

{$ifdef use_window_message}

postmessage(fmsgwin,wm_quit,0,0);

{$else}

postthreadmessage(threadid,wm_quit,0,0);

{$endif}

end;

{------------------------------------------------------------------------------}

procedure tmsgthread.quitthreadwait;

begin

quitthread;

waitterminate;

end;

{------------------------------------------------------------------------------}

procedure tmsgthread.setdoloop(const value: boolean);

begin

if value = fdoloop then exit;

fdoloop := value;

if fdoloop then

postmsg(wm_user,0,0);

end;

{------------------------------------------------------------------------------}

//can only call this method in main thread!!

procedure tmsgthread.waitterminate;

var

xstart:cardinal;

begin

xstart:=gettickcount;

try

//enablewindow(application.handle,false);

while waitforsingleobject(handle, 10) = wait_timeout do

begin

application.processmessages;

if gettickcount > (xstart + 4000) then

begin

terminatethread(handle, 0);

beep;

break;

end;

end;

finally

//enablewindow(application.handle,true);

end;

end;

{------------------------------------------------------------------------------}

procedure tmsgthread.postmsg(msg: cardinal; wparam, lparam: integer);

begin

{$ifdef use_window_message}

postmessage(fmsgwin,msg,wparam,lparam);

{$else}

entercriticalsection(fctlsect);

try

feventlist.add(nil);

postthreadmessage(threadid,msg,wparam,lparam);

finally

leavecriticalsection(fctlsect);

end;

{$endif}

end;

{------------------------------------------------------------------------------}

procedure tmsgthread.sendmsg(msg: cardinal; wparam, lparam: integer);

{$ifndef use_window_message}

var

aevent:phandle;

{$endif}

begin

{$ifdef use_window_message}

sendmessage(fmsgwin,msg,wparam,lparam);

{$else}

entercriticalsection(fctlsect);

try

new(aevent);

aevent^ := createevent(nil, true, false, nil);

feventlist.add(aevent);

postthreadmessage(threadid,msg,wparam,lparam);

finally

leavecriticalsection(fctlsect);

end;

waitforsingleobject(aevent^,infinite);

{$endif}

end;

end.

2003-6-22 10:56:00

查看评语»»»

2003-6-22 11:02:24我参考了一下msdn,还有windows核心编程.

写了一个类来封装这个功能,不知道对不对.

里面使用了两个方法,一个使用一个隐含窗体来处理消息

还有一个是直接使用thread的消息队列来处理,但是这个时候sendmessage无法工作,所以我自己设想了一个方法,虽然不完全达到了要求但是我简单测试了一下,好像还能工作.

切换两种工作方式要修改编译条件

{$define use_window_message} 使用隐含窗体来处理消息

{-$define use_window_message} 使用线程消息队列来处理消息

.

2003-6-22 11:02:54还有我想要等待线程开始进行消息循环的时候create函数才返回.但是现在好像还没有这样(用一个事件来处理).只是开始进入了threadexecute函数,线程的create就返回了.可能会出问题.

2003-6-23 8:55:22通过设置 doloop属性可以设定线程是否循环(不阻塞等待消息),这样派生类线程在循环做一些其他事情的同时还可以接受消息. 例如:派生类里面循环发送缓冲区的数据,还可以响应其他线程发送过来的消息(如停止,启动,退出,等等)

2003-8-4 10:21:18重新修改了一下,现在用起来基本没有问题了。

{-----------------------------------------------------------------------------

unit name: umsgthread

author:xwing

email :xwing@263.net ; msn : xwing1979@hotmail.com

purpose:thread with message loop

history:

2003-7-15write thread class without use delphi own tthread.

2003-6-19, add function to send thread message.ver 1.0

use event list and waitforsingleobject

your can use windowmessage or threadmessage

2003-6-18, change to create a window to recving message

2003-6-17, begin.

-----------------------------------------------------------------------------}

unit umsgthread;

interface

{$warn symbol_deprecated off}

{$define use_window_message}

uses

classes, windows, messages, forms, sysutils;

const

nm_execproc = $8fff;

type

emsgthreaderr = class(exception);

tmsgthreadmethod = procedure of object;

tmsgthread = class

private

syncwindow: hwnd;

fmethod: tmsgthreadmethod;

procedure syncwindowproc(var message: tmessage);

private

m_hthread: thandle;

threadid: dword;

{$ifdef use_window_message}

fwinname: string;

fmsgwin: hwnd;

{$else}

feventlist: tlist;

fctlsect: trtlcriticalsection;

{$endif}

fexception: exception;

fdoloop: boolean;

fwaithandle : thandle;

{$ifdef use_window_message}

procedure msgwinproc(var message: tmessage);

{$else}

procedure clearsendmsgevent;

{$endif}

procedure setdoloop(const value: boolean);

procedure execute;

protected

msg:tagmsg;

{$ifndef use_window_message}

umsg:tmessage;

fsendmsgcomp:thandle;

{$endif}

procedure handleexception;

procedure dohandleexception;virtual;

//inherited the method to process your own message

procedure doprocessmsg(var msg:tmessage);virtual;

//if doloop = true then loop this procedure

//your can use the method to do some work needed loop.

procedure domsgloop;virtual;

//initialize thread before begin message loop

procedure doinit;virtual;

procedure douninit;virtual;

procedure postmsg(msg:cardinal;wparam:integer;lparam:integer);

//when use sendmsg method must not use synchronize method in threadloop !!!

//otherwise will caurse deadlock

function sendmsg(msg:cardinal;wparam:integer;lparam:integer):integer;

public

constructor create(loop:boolean=false;threadname: string='');

destructor destroy;override;

// return true if the thread exists. false otherwise

function threadexists: bool;

procedure synchronize(syncmethod:tmsgthreadmethod);

function waitfor:longword;

function waittimeout(timeout:dword=4000):longword;

//postmessage to quit,and free(if freeonterminater = true)

//can call this in thread loop, don't use terminate property.

procedure quitthread;

//just like application.processmessage.

procedure processmessage;

//enable thread loop, no waitfor message

property doloop: boolean read fdoloop write setdoloop;

end;

implementation

function msgthdinitialthreadproc(pv:pointer):dword;stdcall;

var

obj:tmsgthread;

begin

obj := tmsgthread(pv);

obj.execute;

result := 0;

end;

{ tmsgthread }

{//}

constructor tmsgthread.create(loop:boolean;threadname:string);

begin

{$ifdef use_window_message}

if threadname0 then

quitthread;

waitfor;

//free sync window

destroywindow(syncwindow);

freeobjectinstance(pointer(getwindowlong(syncwindow, gwl_wndproc)));

{$ifdef use_window_message}

{$else}

feventlist.free;

deletecriticalsection(fctlsect);

closehandle(fsendmsgcomp);

{$endif}

inherited;

end;

{//}

procedure tmsgthread.execute;

var

mret:boolean;

aret:boolean;

begin

{$ifdef use_window_message}

fmsgwin := createwindow('static',pchar(fwinname),ws_popup,0,0,0,0,0,0,hinstance,nil);

setwindowlong(fmsgwin, gwl_wndproc, longint(makeobjectinstance(msgwinproc)));

{$else}

peekmessage(msg,0,wm_user,wm_user,pm_noremove); //force system alloc a msgqueue

{$endif}

mret := true;

try

doinit;

//notify conctructor can returen.

setevent(fwaithandle);

closehandle(fwaithandle);

while mret do//message loop

begin

if fdoloop then

begin

aret := peekmessage(msg,0,0,0,pm_remove);

if aret and (msg.message0 then

begin

aevent := feventlist.items[0];

if aeventwm_quit then

begin

{$ifdef use_window_message}

translatemessage(msg);

dispatchmessage(msg);

{$else}

umsg.msg := msg.message;

umsg.wparam := msg.wparam;

umsg.lparam := msg.lparam;

doprocessmsg(umsg);

{$endif}

end;

end;

{//}

procedure tmsgthread.doinit;

begin

end;

procedure tmsgthread.douninit;

begin

end;

procedure tmsgthread.domsgloop;

begin

sleep(0);

end;

{//}

function tmsgthread.threadexists: bool;

begin

if m_hthread = 0 then

result := false

else

result := true;

end;

{------------------------------------------------------------------------------}

procedure tmsgthread.quitthread;

begin

{$ifdef use_window_message}

postmessage(fmsgwin,wm_quit,0,0);

{$else}

postthreadmessage(threadid,wm_quit,0,0);

{$endif}

end;

{------------------------------------------------------------------------------}

procedure tmsgthread.setdoloop(const value: boolean);

begin

if value = fdoloop then exit;

fdoloop := value;

if fdoloop then

postmsg(wm_user,0,0);

end;

{------------------------------------------------------------------------------}

function tmsgthread.waittimeout(timeout:dword):longword;

var

xstart:cardinal;

h: thandle;

begin

h := m_hthread;

xstart:=gettickcount;

while waitforsingleobject(h, 10) = wait_timeout do

begin

application.processmessages;

if gettickcount > (xstart + timeout) then

begin

terminatethread(h, 0);

break;

end;

end;

getexitcodethread(h, result);

end;

{------------------------------------------------------------------------------}

function tmsgthread.waitfor: longword;

var

msg: tmsg;

h: thandle;

begin

h := m_hthread;

if getcurrentthreadid = mainthreadid then

while msgwaitformultipleobjects(1, h, false, infinite, qs_sendmessage) = wait_object_0 + 1 do

peekmessage(msg, 0, 0, 0, pm_noremove)

else

waitforsingleobject(h, infinite);

getexitcodethread(h, result);

end;

{------------------------------------------------------------------------------}

procedure tmsgthread.postmsg(msg: cardinal; wparam, lparam: integer);

begin

{$ifdef use_window_message}

postmessage(fmsgwin,msg,wparam,lparam);

{$else}

entercriticalsection(fctlsect);

try

feventlist.add(nil);

postthreadmessage(threadid,msg,wparam,lparam);

finally

leavecriticalsection(fctlsect);

end;

{$endif}

end;

{------------------------------------------------------------------------------}

function tmsgthread.sendmsg(msg: cardinal; wparam, lparam: integer):integer;

{$ifndef use_window_message}

var

aevent:phandle;

{$endif}

begin

{$ifdef use_window_message}

result := sendmessage(fmsgwin,msg,wparam,lparam);

{$else}

entercriticalsection(fctlsect);

try

new(aevent);

aevent^ := createevent(nil, true, false, nil);

feventlist.add(aevent);

postthreadmessage(threadid,msg,wparam,lparam);

finally

leavecriticalsection(fctlsect);

end;

waitforsingleobject(aevent^,infinite);

result := umsg.result;

setevent(fsendmsgcomp);

{$endif}

end;

{------------------------------------------------------------------------------}

procedure tmsgthread.synchronize(syncmethod: tmsgthreadmethod);

begin

fmethod := syncmethod;

sendmessage(syncwindow,nm_execproc,0,longint(self));

end;

{------------------------------------------------------------------------------}

procedure tmsgthread.syncwindowproc(var message: tmessage);

begin

case message.msg of

nm_execproc:

with tmsgthread(message.lparam) do

begin

message.result := 0;

try

fmethod;

except

raise emsgthreaderr.create('执行同步线程方法错误。');

end;

end;

else

message.result:=defwindowproc(syncwindow,message.msg,message.wparam,message.lparam);

end;

end;

end.


======================================================
在最后,我邀请大家参加新浪APP,就是新浪免费送大家的一个空间,支持PHP+MySql,免费二级域名,免费域名绑定 这个是我邀请的地址,您通过这个链接注册即为我的好友,并获赠云豆500个,价值5元哦!短网址是http://t.cn/SXOiLh我创建的小站每天访客已经达到2000+了,每天挂广告赚50+元哦,呵呵,饭钱不愁了,\(^o^)/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值