Search code examples
multithreadingdelphidelphi-2010resumeomnithreadlibrary

How to pause/resume threads in OmniThreadLibrary 3?


I want the main application thread to be able to pause / resume the other working threads, assuming this is possible, what's the best way to do this?

Any suggestion that would work on Windows XP (and later) would be more than welcome!

PS. I'm using Delphi 2010 and OmniThreadLibrary 3


Solution

  • OmniThreadLibrary exposes no commands for suspending a thread. The API method of suspending a thread is to call SuspendThread, and that function is only called in two places, neither of which is available for direct use from outside the library.

    If you have a TOTPWorkerThread, you can call SuspendThread on its Handle property.

    There is no safe, recommended way of suspending a thread from outside the thread's own context. Doing so invariably leads to problems because the external thread cannot know exactly what the other thread is doing at the moment it attempts to suspend it. It might be in the middle of an I/O statement, or it might hold a lock that other threads are waiting for.

    The safe, recommended way to suspend a thread is to send it some sort of notification that you want it to suspend itself. Within the context of OmniThreadLibrary, that could mean calling Cancel on a worker thread.

    The better way to suspend a thread is to not suspend it at all. The usual case for suspending a thread is that there's nothing left for it to do at the moment, so when something becomes available, you want to wake it up so it can continue processing the new work. You can do that without suspending, though. Instead, make the thread wait on the queue that contains the work items. OmniThreadLibrary has a couple of mechanisms for that. You can put each unit of work into a separate task, and then put those tasks in the thread pool. You can also put your tasks in a simple queue, and then have one thread working on the queue.