On 29 Apr 2009, at 00:57, Eric Hermanson wrote:

When implementing the while-loop in the main function of an NSThread, is it correct to assume it is more efficient on the operating system to run the current run-loop until a specified date rather than just use NSThread sleepUntilDate to obtain the delay?

If you're talking about a secondary thread, NSThread's -sleepUntilDate is probably better. But you don't even need to use that; you could use sleep() or nanosleep() or even select().

However...

I ask because I don't really need a formal run loop or special input source as I'm just checking a shared queue for data (and the delay is to allow the thread to gracefully exit).

...you shouldn't be polling your shared queue, *unless* you have some real-time requirement that necessitates that architecture, *or* you're certain that, for the entire lifetime of your thread, the chances are that the queue will always be full by the time the thread gets to check it. If you aren't sure you need to poll, you probably don't want to be polling.

What you should be doing instead is either using a semaphore or an NSConditionLock to set things up such that your thread doesn't run at all unless there's work to do.

So it's simpler to code just the NSThread sleep, however, I am guessing that will cause me context switching performance issues and I'd be better off using the NSRunLoop?

If the NSRunLoop has nothing to do, I imagine it does the same thing anyway.

Finally, is it acceptable to use the NSThread's cancelled/ isCancelled mechanism to check for the thread-exit hint, rather than set/check a global variable in the NSThread threadDictionary (as Apple's documentation shows)?

That's what -cancel and -isCancelled are designed for. That said, if I were implementing a thread to managed a work queue (which is what you're doing), I'd be inclined to override the default implementations so that they added an item to the work queue... that way the thread could block on the work queue and would wake up if someone sent - cancel to it.

But all of this is somewhat academic in a way, because Apple has handily provided NSOperationQueue for you which is probably what you should be using unless you have some backwards compatibility requirement or some other requirement that NSOperationQueue doesn't satisfy.

Kind regards,

Alastair.

--
http://alastairs-place.net



_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to