Delphi thread that waits for data, processes it, then resumes waiting

Marek Jedliński picture Marek Jedliński · Nov 14, 2009 · Viewed 9.5k times · Source

I need to create a thread in Delphi with the following characteristics:

  • Waits until the main thread adds data to a shared queue.
  • Processes all the data in the queue, returning the results to main thread (for this last part I'll just send messages to the main window). Processing is time-consuming, so new data may be added to the queue while the worker thread is processing previous entries.
  • Resumes waiting, using as little cpu cycles as possible.

I cannot send messages to the thread, since it does not have a window handle.

Should I be using some variant of WaitForObject? If so, what would the wait be for? If not, then how can I keep the thread waiting, then awake it when new data comes down the queue?

I've read Multithreading - The Delphi Way, which doesn't seem to answer my question. Perhaps OmniThreadLibrary can do what I need; I can't tell since there's little documentation. I don't know enough about threads in general to figure out if the library will help here and how to use it (or even why to use it instead of just working with TThread descendants).

Answer

gabr picture gabr · Nov 14, 2009

OmniThreadLibrary can definitely help you here. Test 5 from the OTL distribution should help you started.

In this demo, "Start" button creates the thread and sets some parameters and timer (which you can remove in your code if not needed). "Change message" sends a message to the thread and this message is processed in thread's OMChangeMessage method. Thread then sends some information back to the client (OMSendMessage in this demo, but you can do this in the same message you'll be doing your work in) and main thread receives this message via the OmniEventMonitor component. "Stop" button stops the worker thread.

If more messages arrive while your thread is busy, they will be queued and processed as soon as your worker method has completed its work. When there's nothing to do, thread will wait for the next message using zero CPU cycles in the process.

EDIT

In Delphi 2009 and above, the Background Worker pattern provides a simpler solution.