raaz
raaz

Reputation: 12500

what is the difference among sleep() , usleep() & [NSThread sleepForTimeInterval:]?

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

What is the best condition to use these methods ?

Upvotes: 22

Views: 19105

Answers (4)

Salah Amean
Salah Amean

Reputation: 1

-Example usage of sleep is in the following state:

In network simulation scenario, we usually have events that are executed event by event,using a scheduler. The scheduler executes events in orderly fashion. When an event is finished executing, and the scheduler moves to the next event, the scheduler compares the next event execution time with the machine clock. If the next event is scheduled for a future time, the simulator sleeps until that realtime is reached and then executes the next event.

-From linux Man pages:

The usleep() function suspends execution of the calling thread for (at least) usec microseconds. The sleep may be lengthened slightly by any system activity or by the time spent processing the call or by the granularity of system timers. while sleep is delaying the execution of a task(could be a thread or anything) for sometime .Refer to 1 and 2 for more details about the functions.

Upvotes: -1

snort
snort

Reputation: 31

On most OSs, sleep(0) and its variants can be used to improve efficiency in a polling situation to give other threads a chance to work until the thread scheduler decides to wake up the polling thread. It beats a full-on while loop. I haven't found much use for a non-zero timeout though, and apple in particular has done a pretty good job of building an event driven architecture that should eliminate the need for polling in most situations anyway.

Upvotes: 3

bbum
bbum

Reputation: 162712

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?

Upvotes: 22

Jason Coco
Jason Coco

Reputation: 78363

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.

Upvotes: 32

Related Questions