2

I have a dispatch_async call to a secondary thread and just for testing purposes I wanted to sleep the secondary thread for 5 seconds. Here is the code:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  sleep(5);
});

When I test this on Mac OSX Lion 10.7.2, the sleep() function does not put the thread to sleep. And on the iPhone simulator using same code it does.

On the mac, sleep works on the main thread, and on the secondary thread using [NSThread sleepUntilTimeInterval:] works too.

Why won't the sleep() function work on secondary threads on the mac? Thank you.

Peter Hosey
  • 95,783
  • 15
  • 211
  • 370
the Reverend
  • 12,305
  • 10
  • 66
  • 121
  • take a look at [Grand Central Dispatch vs. NSThread](http://stackoverflow.com/questions/5653522/grand-central-dispatch-vs-nsthread) and [Is there any reason to not use sleep in a Grand Central Dispatch queue?](http://stackoverflow.com/questions/4668634/iphone-is-it-ok-to-use-usleep-on-a-secondary-thread-on-grand-central-dispatch) – Parag Bafna Jan 14 '12 at 19:24

3 Answers3

4

Global queues run tasks concurrently on multiple threads if possible. Macs typically have 4-16 cores so it makes sense that the queue would have multiple workers. It is better to think of the global queues as thread pool.

It sounds like you might want to look into serial queues if you want tasks in a queue to execute in a specific order.

Evan
  • 6,151
  • 1
  • 26
  • 43
2

Are you using any signals for ipc?

Any signals will interrupt sleep(), but not [NSThread sleepForTimeInterval:].

Todd Masco
  • 218
  • 3
  • 11
  • after the call to sleep() I'm using a mutex don't know if thats considered a signal? But anyway the same code does work for iOS – the Reverend Jan 15 '12 at 02:16
  • No, a mutex isn't a signal, signals are delivered cross-process. I was also thinking perhaps something in your Mac OS X environment that is not present in your iOS environment could using signals, like cputhrottle. The iOS environment is a bit more controlled in its ipc. This could be a blind alley, but this is one reason to use Cocoa-specific calls like [NSThread sleepForTimeInterval:] over Posix calls like sleep() - the native calls are better suited to the run time environment than the more cross-platform Posix library. – Todd Masco Jan 15 '12 at 03:04
0

How do you know that the sleep(5) is not executing on iOS? I see nothing before or after the sleep() in your block to indicate that a thread didn't block, and when you dispatch_async() against a concurrent queue, which thread you execute on (including the current one) is non-deterministic by design, so make no assumptions about that.

jkh
  • 3,246
  • 16
  • 13