[Lazarus] Help: Multithreading

Michael Schnell mschnell at lumino.de
Thu Aug 16 09:36:31 CEST 2012


On 08/15/2012 05:20 PM, Clinton Shane Wright wrote:
> I dont understand how to make another instance of the same thread 
That is easy, but you might need to take so  afterthoughts:

You can just do something like

var MyThread = array [0..10] of TMyThread;

   for i = 0 to 10 do MyThread[i] = TMyThread.Create(False);

So you have multiple threads that use the same executable code.

Of course global variable are shared between all of them and 
MyThread[i].xyz (or just xyz from within a TMyThread.ppp procedure) 
variables are dedicated to each.

Moreover you can do "threadvar" variables that automatically are 
dedicated to a single thread and not accessible from other threads 
(including the main thread that gets it's own copy.

These threadvars e.g. can allow  to determine which thread is just 
running in a procedure called by the thread Execute that does not get 
the TMythread self pointer.


>
> If I may add, I am using the thread to read data from a modem from the 
> RS232, but now I have more than one modem connected to the system that 
> I need to read from at once and having it run in one thread gets 
> slower as I add one modem extra to the thread, I want to use the 
> second instance, TMyThread2 to control the modem 2.

The main problem will be to do the communication between the multiple 
threads and the main thread.

Here IMHO a good idea is to do the basic receive-protocol in a thread 
(that most of the time will be blocked waiting for input from the serial 
interface), and to the more complex stuff (that needs data from and 
sends data to multiple serial interfaces) in the main thread.

Here IMHO the way to go is to collect a block of data (by the thread) in 
a memory area allocated by the thread using an Object or "new", and then 
push (a pointer to) same in a TThreadList. After pushing the thread 
creates a main thread event by "ApplicationQueueAsyncCall". On that some 
time later the event will be called on the "Level" of the main thread. 
Here all available data blocks can be retrieved and the transport memory 
on the heap can be released.

Sending data to the serial interface usually can be done right in the 
main thread becaus the OS provides a decent FoFo buffer for each interface.

-Michael




More information about the Lazarus mailing list