Is there an NSThread equivalent of suspend/resume?

Chris Hanson cmh at mac.com
Sun May 6 22:58:26 PDT 2007


On May 5, 2007, at 10:27 AM, Duncan Champney wrote:

> Ideally, I'd like to have my main thread suspend a rendering thread  
> after it completes, and then resume it once it has queued up a new  
> rendering task. I couldn't find support for this in the  
> documentation for threads. Is there an equivalent of suspend/resume  
> calls for threads as opposed to NSTasks? If so, what are the calls  
> and where are they documented? Some sort of "wake early" call would  
> also solve my problem (a call, performed from the main thread, that  
> would wake a rendering thread from sleep before its sleep interval  
> had elapsed)

There is not.  Fine-grained manipulation of threads -- for example,  
suspending them, resuming them, canceling/killing them, and so on --  
is ***almost always*** incorrect and it's good not to have APIs for  
people to abuse in this fashion.

What you're describing is a classic producer/consumer problem, well- 
described in the multiprogramming literature for the past 40 years or  
so.   The standard solution to this is to have the producer place work  
items in a queue that the consumers block on when they are not  
performing the requested work.  When an item is placed in the queue,  
one of the consumers blocked on the queue is unblocked, removes the  
item, and processes it.

In Cocoa, this can be done easily by simply creating several worker  
threads and sharing an NSMutableArray protected by an  
NSConditionLock.  (People usually combine the array and the lock into  
their own WorkQueue class, of course.)

   http://www.cocoadev.com/index.pl?ProducersAndConsumerModel

Try the easiest solution first, obviously.  Don't immediately try to  
go beyond the first example (ThreadSafeQueue) on that page, since you  
should understand thoroughly why the first example works before  
attempting anything else.  You probably won't even need anything  
beyond the first example -- I've never needed more than an equivalent  
class I wrote five years ago at MacHack for my "stream a fake screen  
over the network" hack.

   -- Chris



More information about the MacOSX-dev mailing list