Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross thread communication in Delphi

Is there any documentation on cross thread communication in Delphi? How can I send message to the thread that doesn't have a window?

like image 461
samir105 Avatar asked Jan 13 '09 13:01

samir105


2 Answers

You can only send (Windows) messages to threads that implement a standard message loop, which will automatically be created once a window handle is realized.

It is however not necessary to use messages to communicate with a thread. Just let it wait on an event object (TEvent in VCL), and signal this event when you want the thread to perform a function.

But if you are new to multi-threading - don't go into all these details on your own, unless you want to for the learning effect. Just use the OmniThreadLibrary and be done with it. There's much good to be learned by digging into its internals, once you know how to use it.

Edit:

See also the answers to this question which is very similar.

Edit 2:

Regarding the comment asking "What does [OmniThreadLibrary] make easier, and at what cost?" I can only advise you to check it out for yourself - that is if you are using at least Delphi 2007. There are several samples to illustrate the concepts, but for a quick "real-life" example you could have a look at this blog post - you don't even need to install the library for that.

I do also agree that using a library for multi-threading does require a certain act of faith. OTOH making do with what the VCL provides is hardly an alternative. The sample code does still use the ill-conceived Synchronize() call. There is no support for things like thread-safe producer-consumer-queues, which are much more suited to multi-threaded programming. And if you do agree that you need a more solid fundament for your multi-threaded programs than the VCL provides - why reinvent that particular wheel?

As for the cost of using the library: You will have to time yourself whether it is fast enough for you. It does abstract the communication between threads in a good way IMHO, but every abstraction costs performance, obviously.

If you decide that it is not for you after all - write the code yourself. I did the same for Delphi 4, and I have been using that code for nearly 10 years now. And judging by the amount of bugs I found and corner cases I experienced in that time, I would definitely advise anybody new to multi-threading to not write their own library code for it. And if you really really want to, please take the rules in this posting to heart.

like image 122
mghie Avatar answered Oct 17 '22 07:10

mghie


The question Delphi Multi-Threading Message Loop also contains a few examples of communication between threads

like image 25
Davy Landman Avatar answered Oct 17 '22 05:10

Davy Landman