Jyotsna Kadam
Jyotsna Kadam

Reputation:

How to put only one thread to sleep?

I want to create two threads in my game. One thread is for timer and other for touch events. Because when I am running my game on iPhone, timer conflicts with touch events and touch events are not reported. It works smooth in simulator but on iPhone or on iPod Touch it's becomes very slow. So I'm using separate threads for touch events and timer.

When I use [NSThread sleepForTimeInterval:0.01] it makes all threads sleep. I mean touch events are also stop to come through. I want to stop the timer thread only.

This is my code:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    BOOL Done = NO;
    while (!Done)
    {
        NSAutoreleasePool *loopPool = [[NSAutoreleasePool alloc] init];
        [NSThread sleepForTimeInterval:0.01];
        [self performSelectorOnMainThread:@selector(callTapCode) withObject:tapView waitUntilDone:YES];

        //performSelectorOnMainThread:@selector(callTapCode) withObject:nil waitUntilDone:YES];

        [loopPool release];
        Done=YES;
    }

    [pool drain];
}

Upvotes: 0

Views: 3280

Answers (2)

koki
koki

Reputation: 352

[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.01]];

Upvotes: 0

rpetrich
rpetrich

Reputation: 32316

If you are trying to create a timer, you should probably just use NSTimer, because that's simpler and more efficient than creating a thread just to send a "go" event every so often.

edit: As is, you aren't creating a second you are merely stalling the main thread by calling [NSThread sleepForTimeInterval:0.01] in a loop. This means your main thread is no longer running the event loop which can cause all kinds of things to no longer work.

Upvotes: 1

Related Questions