I've found an interesting multithreading issue which is related not only to 
ICS component but many many other components I've seen so far. It is a race 
condition between two thread where one is triggering an event handler and 
the other is removing (setting to nil) the event handler.

Consider the following procedure:

Line1: procedure TMyComponent.TriggerMyEvent(MyArg : Integer);
Line2: begin
Line3:     if Assigned(OnMyEvent) then
Line4:         OnMyEvent(Self, MyArg);
Line5: end;

Imagine this is used in a context where the component run in thread #1 and 
where thread #2 change the OnMyEvent event handler to nil just when thread 
#1 has evaluated the expression at line 3 as true, experienced a context 
switch and come back up and running at line 4. At that time OnMyEvent is nil 
and you get an exception !

The solution is to rewrite the procedure as follow:

Line1: procedure TMyComponent.TriggerMyEvent(MyArg : Integer);
Line2: var
Line3:     TMyEventProc EventProc;
Line4: begin
Line5:     EventProc := OnMyEvent;
Line6:     if Assigned(EventProc) then
Line7:         EventProc(Self, MyArg);
Line8: end;

Saving the event pointer in line5 make sure that it is still valid in the 
case a thread switch between Line 6 and 7 occur and the OnMyEvent is set to 
nil by the other thread.

Interesting, isn't it ?

Contribute to the SSL Effort. Visit http://www.overbyte.be/eng/ssl.html
--
[EMAIL PROTECTED]
The author for the freeware multi-tier middleware MidWare
The author of the freeware Internet Component Suite (ICS)
http://www.overbyte.be


-- 
To unsubscribe or change your settings for TWSocket mailing list
please goto http://www.elists.org/mailman/listinfo/twsocket
Visit our website at http://www.overbyte.be

Reply via email to