Question

I'm using XCode 4.2 in Lion. When I compile my app with the Debug profile (Pressing Apple+R to run it), then when I call nanosleep it never returns from that function. Ever. If I profile the code (building Release profile) then it does return. I'm just using the default profile settings for an XCode project. Any idea what could possibly be going on here?

To reproduce this, create a brand new blank application and put the following code into appDelegate.m:

#import "AppDelegate.h"
#import <time.h>

@implementation AppDelegate

@synthesize window = _window;

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    NSLog(@"Hello");
    struct timespec a;
    a.tv_nsec = 10000;

    /** THE FIX! **/
    a.tv_sec = 0;
    /** THE FIX! **/

    nanosleep(&a,NULL);
    NSLog(@"World");
}

@end

Expected behaviour: Print "World" to the debug console 0.01 ms after Hello.

Actual behaviour: Only "Hello" gets printed and no window appears.

Was it helpful?

Solution

Try explicitly setting a.tv_sec to 0. Probably it is initialized to some garbage and making nanosleep the sleep for a very long amount of seconds.


Or, you could use usleep

#include <unistd.h>

...

NSLog(@"Hello");
usleep(10);      // 0.010 ms = 10 µs = 10000 ns
NSLog(@"World");

OTHER TIPS

You structure is allocated on the stack, so you may have junk/residual data.

As the timespec struct also have a tv_secmember, you should also set it to 0:

struct timespec a;

a.tv_sec  = 0;
a.tv_nsec = 10000;

nanosleep( &a, NULL );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top