views:

271

answers:

3

What is the best solution to allow an object to execute methods on a thread? The object is the owner of the TThread and the thread contains only a TidHTTP (blocking socket) to post request and parse the response.

Example :

  • Object > Execute Request on the Thread
  • Thread > Send request via idHTTP, wait for response, send the result to the Object
  • Thread > Wait for another request
  • Object > Update the UI depending of the result of the request
+4  A: 

A relative safe way to communicate with threads is using command queues.

  • The object post a request in the queue (using semaphores).
  • The tread checks the queue (using semaphores) and if it is filled executes the oldest request (you can introduce priorities if you want).
  • If the task is finished, the object is signalled (for example with a callback function).

The thread normally sleeps, and only awakes to check the queue. If there is nothing to do, it "presses the snooze button" and sleeps again.

Be sure to guard the access to the queue with semaphores. Else there is a chance of data corruption and you have a hard bug to find.

Gamecat
Thanks for your answer :)
Ariel32
A: 

I don't know about "best" - depends what your criteria are. If you expand a little on your requirements, we could maybe offer more specific help. In the meantime...

The simplest method is to allow the owning object to write the request to the thread, either into one or more properties or by a public method. The data fields behind the properties/method are not accessed directly by the main Execute routine: use a method called by Synchronize() to copy these data fields into variables that can be used by the Execute() routine. I use this method when speed is not the main objective, and the owning object does not need to queue multiple requests.

Many people disparage using Synchronize, but it depends on the functionality you are trying to achieve. I try to keep things simple until the requirements demand otherwise.

If throughput is more of an issue, or if you need to have overlapping requests, you could use a queue to store the requests, with access to the queue controlled by a TCriticalSection. You could also use TThreadList, either directly or as a basis for your own typed storage - I am not aware of a generic equivalent of TThreadList, though there may well be one.

IanH
Thanks for your help ! I need to use a queue to store the request and the thread can only execute one request at the same time. I can't spawn more thread that will use the same idHTTP so even if all requests are independent, they must be executed one by one only. The application I'm working on is more explained on this post : http://stackoverflow.com/questions/1506212/complex-software-architecture
Ariel32
+1  A: 

Another method, worth mentioning, is to use Async Calls by Andreas Hausladen. It is a simple to use and well written thread wrapper that works very well in a functional environment.

skamradt