Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to improve perfomance using multithreading?

I've got a program which receives string messages from other applications and parses them using VCL. Messages are sent as follows:

AtomId := GlobalAddAtom(PChar(s));
SendMessage(MyProgramHandle, WM_MSG, 0, AtomID);
GlobalDeleteAtom(AtomID);

My program receives this message, parses it for some time, and then returns control to an application. It takes time to parse one message so perfomance of other applications worsens.

One possible solution is to create form with the same caption and the same class in other thread, and rename class of main form. But as far as I know it isn't recommended to create forms in threads.

So, what are possible ways to improve perfomance?

like image 299
vralex Avatar asked Feb 22 '23 16:02

vralex


1 Answers

The typical approach would be to create a worker thread (or a pool of worker threads). The main thread will continue to receive the messages, but instead of parsing them it will just add them to a queue (a linked list, for example).

The worker thread takes the first element in the queue and processes it. When done it goes back to the queue to get the next element.

Since the queue is a shared resource between multiple threads you have to control access to it. A mutex will ensure that only one thread gets access to the queue at any given time.

Good luck.

like image 138
Miguel Avatar answered Mar 08 '23 06:03

Miguel