1

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

ThinkingStiff
  • 64,767
  • 30
  • 146
  • 239
TheDude
  • 3,045
  • 4
  • 46
  • 95
  • 7
    You never pause threads from the outside. Main thread signals that it wants a thread to pause, and then the thread responds by waiting until it is signaled to resume. – David Heffernan Sep 02 '12 at 10:39
  • 1
    For an example how to do this with an event signal (not an OTL framework example though) see, [Do I need TThreads? If so can I pause, resume and stop them?](http://stackoverflow.com/a/11278283/576719). – LU RD Sep 02 '12 at 10:54
  • Thank you Guys for your help / link. I believe it's possible to pause from the outside, I'm kinda hoping to see if there's a **safe / recommended** way to do it in OTL. – TheDude Sep 02 '12 at 13:47
  • 1
    If you pause it from the outside, and if your thread uses **any** locks, then you are subject to deadlock. You will need to realign your expectations. Read the Windows API docs for SuspendThread for example. – David Heffernan Sep 02 '12 at 15:28

1 Answers1

6

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.

Rob Kennedy
  • 161,384
  • 21
  • 275
  • 467