sleep() VS. usleep() VS. [NSThread sleepForTimeInterval:]

Discussion in 'Mac Programming' started by Darkroom, Jul 18, 2008.

  1. Guest


    Dec 15, 2006
    Montréal, Canada
    i don't really understand the difference between these 3 functions... assuming i have a program running, with several timers going on in the background for different things, and i execute an IBAction which would execute some stuff and then pause for 2 seconds before redirecting to another method in the class... which of these 3 functions are better to use and why?

    [COLOR="Green"]//do something;
    //do something else;[/COLOR]
    [NSThread sleepForTimeInterval:2]; [COLOR="green"]//or[/COLOR]
    sleep(2); [COLOR="green"]//or[/COLOR]
    [COLOR="green"]//then redirect to another method within the class[/COLOR]
    i should probably mention that while "usleep" seems to be an actual function and compiles without error: usleep(<#useconds_t #>), it doesn't work for me at all...
  2. macrumors 6502

    Jul 25, 2006
    They're essentially all wrappers around nanosleep() and just provide different conveniences.

    I think useconds_t is just a typedef for unsigned long or unsigned long long, so passing other integer types won't cause errors.

    Haha... sorry. I didn't see the actual question in there—it was too early in the morning. Do what Catfish Man said.
  3. macrumors 68030


    Sep 13, 2001
    Portland, OR
    None of the above. Sleeping the main thread will just lag your program. Instead, schedule an NSTimer to fire two seconds later with the work you need done.
  4. macrumors 68040


    Oct 25, 2004
    The parameter of usleep() is in microseconds. That's millionths of a second. So usleep(2000) will sleep for 2 milliseconds (two thousandths of a second)--too fast for a human to perceive. sleep(2) would be equivalent to usleep(2000000).
  5. thread starter Guest


    Dec 15, 2006
    Montréal, Canada
    ooohhhh! i though it was just my lefts and rights that i got mixed up, now i've got to deal with microseconds and milliseconds too :p... but at least now i know why it wasn't working... thanks for that...
  6. thread starter Guest


    Dec 15, 2006
    Montréal, Canada
    i had noticed that [NSThread sleepForTimeInterval:2]; actually pauses my application instead of just the class it's in, which i had assumed the later would be the case...

    after playing around with this function, i had noticed that the spinning beachball would show up if i set it this function to around 5 seconds... strange? yes/no?

    i've therefore decided to use [NSThread sleepForTimeInterval:0.5]; instead of using NSTimer - simply because NSTimer gave unexpected/unwanted results in certain situations.
  7. macrumors 68040


    Jan 10, 2005
    Dallas, TX
    Catfish_Man warned about this behavior above. I would look into NSTimer as be suggested.


Share This Page