2011-06-01 62 views
-1
-(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"); 

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

插入和顯示方法都是在調用insert方法之前調用startThread.display。但是我希望顯示等待插入完成其執行。如果它停止了一個信號必須被髮送到開始線程顯示錯誤信息。Objective C中的線程

如何做到這一點。

但是在上面的代碼中,顯示方法首先被調用,並且在無限循環中繼續。

回答

0

如果您想在顯示之前調用插入,只需將它移動到調用的上方以啓動線程即可。

​​
+0

如果我那麼做,我需要讓startThread進入休眠狀態,否則線程不會被調用,因爲startThread在調用顯示線程後會退出。 – spandana 2011-06-01 06:01:58

+0

爲什麼這是一個問題?你想做什麼? – skorulis 2011-06-01 06:06:51

0

你可以嘗試:performSelector:onThread:withObject:waitUntilDone:self

從我的理解要同步插件和顯示線程,這樣的顯示的插件(startThread)之後調用,並報告給插入(startThread) (不知道我是否正確)。 如果我熱是正確的,這樣的事情應該做的伎倆(未測試,可能需要一些小的修改):

[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 

,這將是另一種方式:

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

如何檢查startThread過程中的兩個等待條件。 – spandana 2011-06-01 08:50:36

+0

如果你想接收事件(例如查看蘋果的'NSRunLoop'參考),你可能還想使用'[[NSRunLoop currentLoop run]' – 2011-06-01 13:37:12

+0

我希望顯示等待來自insert方法的事件。也是我在顯示方法之前啓動我的線程。但我想要插入方法的輸出作爲第一個,並從插入事件獲取信號後,顯示線程將執行其執行。我希望它並行完成。 – spandana 2011-06-01 13:52:24