开发者

Threads in Objective C

-(void)startThread {

m_bRunThread = YES;  

    if(m_bRunThread) {

        NSThread* myThread = [[NSThread alloc]initWithTarget:self selector:@selector(display) object:theConditionLock];
        [myThread start];

        /*((WaitForSingleobject(event,1500) != WAIT_OBJECT_O) || !m_bRunThread) {

        m_bRunThread = false;
        Trace(_T("Unable to start display Thread\n"));
        }*/

        }
        [self insert];
    }

    -(void)insert {

        [theConditionLock lockWhenCondition:LOCK];
        NSLog(@"I'm into insert function of thread!");
        [theConditionLock unlockWithCondition:UNLOCK];
    }

    -(void)display {

        NSLog(@"I'm into display function");

            开发者_StackOverflow社区while (YES) {
                [theConditionLock lockWhenCondition:LOCK];
                NSAutoreleasePool* pool1 = [[NSAutoreleasePool alloc]init];
                NSLog(@"Into the lock");
                [theConditionLock unlockWithCondition:UNLOCK];
                [pool1 drain];
            }
    }

Both the insert and the display methods are called from the startThread.display is called before the calling of the insert method.But i want the display to wait till the insert finishes its execution.And if its stopped a signal has to be sent to the start thread to display the error message.

How to do it.

But in the code above the display method is called first and it continues in the infinite loop.


If you want to call insert before display simply move it above the call to start the thread.

        m_bRunThread = YES;     
        [self insert];
        if(m_bRunThread)
        {
         NSThread* myThread = [[NSThread alloc]initWithTarget:self selector:@selector(display) object:theConditionLock];
         [myThread start];

        }


you could try: performSelector:onThread:withObject:waitUntilDone: on self

From my understanding you want to sync the insert and display threads, such that display is called after insert (startThread), and report back to insert (startThread) (not sure if I got it right). If I hot it right, something like this should do the trick (not tested, might need some small changes):

    [self insert];
     NSThread* myThread = [[NSThread alloc] init];
     [self performSelector:@selector(display) onThread:myThread withObject:nil waitUntilDone:YES];
    //myThread stopped, check its return status (maybe set some variables) and display error message

this would be another way:

    m_bRunThread = YES;     
    [self insert];
            if(m_bRunThread)
    {
     NSThread* myThread = [[NSThread alloc]initWithTarget:self selector:@selector(display) object:theConditionLock];
     [myThread start];
    }
    while(m_bRunThread){//check if display is still running
        [NSThread sleepForTimeInterval:0.5];
    }
    //display thread stopped
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜