How can I execute certain commands in a separate thread?

What is the best solution to let an object execute methods in a thread? The object is the owner of TThread, and the stream contains only TidHTTP (blocking socket) for sending the request and analyzing the response.

Example:

  • Object> Execute stream request
  • Thread> Send request via idHTTP, wait for a response, send result to object
  • Theme> Waiting for another request
  • Object> Updating the user interface depending on the result of the request
+4
source share
3 answers

A relatively safe way to communicate with threads is to use command queues.

  • The object sends the request to the queue (using semaphores).
  • The protector checks the queue (using semaphores), and if it is filled, the oldest request is executed (you can specify priorities if you want).
  • If the task is completed, the object is signaled (for example, with a callback function).

Usually the thread sleeps and only wakes up to check the queue. If there is nothing to do, he “presses the repeat button” and sleeps again.

Be sure to keep access to the queue using semaphores. In addition, there is a possibility of data corruption, and it is difficult for you to find.

+4
source

Another method worth mentioning is the use of Async Calls by Andreas Hausladen. This is an easy-to-use and well-written thread wrapper that works great in a functional environment.

+1
source

I do not know about the "best" - it depends on your criteria. If you change your requirements a bit, we can offer more specific assistance. Meanwhile...

The easiest way is to allow your own object to write the request to the stream, either into one or more properties, or by the public method. The data fields behind the properties / method are not directly processed by the main Execute procedure: use a method called Synchronize () to copy these data fields into variables that can be used in the Execute () procedure. I use this method when speed is not the main goal, and for the owner object it is not necessary to queue several requests.

Many people humiliate the use of Synchronize, but it depends on what functionality you are trying to achieve. I try to keep things simple until requirements require otherwise.

If bandwidth is a bigger issue or you need overlapping requests, you can use the queue to store requests with access to the queue controlled by TCriticalSection. You can also use TThreadList, either directly or as the basis for your own typed repository - I don't know about the general equivalent of TThreadList, although it may be.

0
source

All Articles