Monday, June 30, 2008

OmniThreadLibrary Example #1: Beep, world!

image In my previous post, I promised to publish some examples of OTL usage. Here is the first one - a simplification of the Hello, World program. This example doesn't write anything to the screen, it just makes a noise.

Start by creating a new Delphi VCL application. Drop a button on the form and write OnClick handler.

procedure TfrmTestOTL.btnBeepClick(Sender: TObject);
begin
CreateTask(Beep, 'Beep').Run;
end;

This will create a threaded task with name 'Beep' and main method Beep. Then the code will create a new thread and start executing this task in the context of the newly created thread. That's all, folks!


To make the example fully functional, add OtlTask unit to the uses list and write the Beep method.

procedure TfrmTestOTL.Beep(task: IOmniTask);
begin
MessageBeep(MB_ICONEXCLAMATION);
end;

Run the program, click the button. It will beep!


If you don't believe that the code is executed in a secondary thread, place a breakpoint on the MessageBeep call and check the Thread Status window. It will clearly indicate that the breakpoint was triggered from a secondary thread.


image


This example is included in the OTL repository in folder tests/0_Beep.

Labels: , , , , , ,

7 Comments:

Blogger Leo said...

"This project currently has no downloads."----from google code

03:06  
OpenID gabr said...

True. At this moment, you can only do SVN checkout. Instructions are on the Source tab.

08:23  
Anonymous Thomas Mueller said...

You could use this function to make the thread's name show up in the thread list:

procedure SetThreadName(const _Name: string);
var
ThreadNameInfo: TThreadNameInfo;
begin
ThreadNameInfo.FType := $1000;
ThreadNameInfo.FName := PChar(_Name);
ThreadNameInfo.FThreadID := $FFFFFFFF;
ThreadNameInfo.FFlags := 0;
try
RaiseException($406D1388, 0, SizeOf(ThreadNameInfo) div SizeOf(LongWord), @ThreadNameInfo);
except
// ignore
end;
end;

twm

08:36  
Blogger gabr said...

That is not a bad idea.

I had problems with such code in older Delphis. I don't remember it well, but I think that the debugger stopped on this RaiseException when I was single-stepping through the code. I'll have to try it in D2007 ...

14:07  
Blogger gabr said...

New version of the OtlTask unit with SetThreadName support was just uploaded to the Google Code.

15:06  
Anonymous Dominique M. said...

Amazing threading approach.
I really love it.

10:42  
Blogger gabr said...

Thanks, I'm glad you like it.

Spread the good word around :)

11:10  

Post a Comment

Links to this post:

Create a Link

<< Home