views:

370

answers:

2

Hi all,

Can any body explain me what is the difference among sleep() , usleep() & [NSThread sleepForTimeInterval:] ?

What is the best condition to use these methods ?

+4  A: 

sleep(3) is a posix standard library method that attempts to suspend the calling thread for the amount of time specified in seconds. usleep(3) does the same, except it takes a time in microseconds instead. Both are actually implemented with the nanosleep(2) system call.

The last method does the same thing except that it is part of the Foundation framework rather than being a C library call. It takes an NSTimeInterval that represents the amount of time to be slept as a double indicating seconds and fractions of a second.

For all intents and purposes, they all do functionally the same thing, i.e., attempt to suspend the calling thread for some specified amount of time.

Jason Coco
+12  A: 

What is the best condition to use these methods ?

Never

Or, really, pretty much almost assuredly never ever outside of the most unique of circumstances.

What are you trying to do?

bbum
But Bill, I find that sleeping for a few nanoseconds here and there clears up all of my inexplicable EXC_BAD_ACCESS crashes!
Jason Coco
Heh. I cringe time I see code that uses `usleep()` for "thread synchronization" purposes. My cringe muscles are sadly sore.
bbum
I know exactly what you mean. In this case, I was hoping to exercise the smile muscles rather than the cringe :)
Jason Coco
I wish more people would see this answer because I've seen `sleep()` used once but wasn't sure if it was because they didn't know what they were doing. Now I'm sure they had no clue.
lucius
@lucius: There are some valid uses for sleep, just not what most people use it for these days, which was the gist of my joke.
Jason Coco
Honestly, I'm having a difficult time thinking of a single valid use for sleep() anymore. Far, far, better off to use a system timer and leave the thread free to do other stuff.
bbum