2011-05-30 78 views
1

doBackgroundWork方法不會從startDoingWork方法中調用。爲什麼我的後臺線程不運行?

threading.h 
    ------------ 
    #import <Foundation/Foundation.h> 

    @interface threading : NSObject { 

     NSConditionLock* theConditionLock; 
     NSMutableArray* workItems; 

    } 
    -(void)startDoingWork; 
    -(void)doBackgroundWork; 
    -(void)notifyBackgroundThreadAboutNewWork; 
    @end 


    threading.m 
    ------------- 

    #import "threading.h" 

    enum{ 
     workToDoNow = 1, 
     workNotToDoNow = 0 
    }; 

    @implementation threading 

    -(id)init{ 
     if (self = [super init]) { 
      theConditionLock = [[NSConditionLock alloc]initWithCondition:workNotToDoNow]; 
      workItems = [[NSMutableArray alloc]init]; 
     } 
     return self; 
    } 
    -(void)startDoingWork{ 
     [NSThread detachNewThreadSelector:@selector(doBackgroundWork) toTarget:self withObject:nil]; 
    } 
    -(void)doBackgroundWork{ 
     while (YES) { 
      NSAutoreleasePool* pool = [[NSAutoreleasePool alloc]init]; 
      NSArray* items = nil; 
      NSLog(@"Going to lock!!"); 
      [theConditionLock lockWhenCondition:workToDoNow]; 
      items = [NSArray arrayWithArray:workItems]; 
      [workItems removeAllObjects]; 
      [theConditionLock unlockWithCondition:workNotToDoNow]; 
      NSLog(@"Finished the work!!"); 
      [pool drain]; 
     } 
    } 
    -(void)notifyBackgroundThreadAboutNewWork{ 
     NSLog(@"Into the Background new work!!"); 
     [theConditionLock lock]; 
     [workItems addObject:@"Hello"]; 
     [theConditionLock unlockWithCondition:workToDoNow]; 
     NSLog(@"Finished and came out!!"); 
    } 
    @end 

    main.m 
    ------ 
    #import <Foundation/Foundation.h> 
    #import "threading.h" 

    int main (int argc, const char * argv[]) { 
     NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 
     threading* threads = [[threading alloc]init]; 
     [threads notifyBackgroundThreadAboutNewWork]; 
     [threads startDoingWork]; 
     [pool drain]; 
     return 0; 
    } 

detachNewThread:selector:toTarget:withObject方法在調試時不會被調用。

+0

1)執行是否到達'[threads startDoingWork]'線? 2)你在控制檯中得到什麼? 3)您是否考慮過使用[GCD](http://stackoverflow.com/questions/tagged/grand-central-dispatch)? – zoul 2011-05-30 07:18:35

+0

@zoul:是的,它達到了。當它在detachNewThreadSelector上時,它不會跳到doBackgroundWork線程上。它出自startDoingWork方法。 – spandana 2011-05-30 07:21:42

+0

我在控制檯上單獨獲取notifybackgroundThreadAboutNewWork方法的輸出 – spandana 2011-05-30 07:24:59

回答

3

是不是你的主要目的快,後臺線程沒有機會開始?你知道,即使在運行時間管理設置和啓動新線程之前,應用程序已經完成,所有的線程被殺死/關閉/不管。您可以讓主線程休眠一秒,以查看後臺線程是否開始運行。

+0

這就是答案。 – 2011-05-30 08:35:08

+0

謝謝。它在睡覺時起作用。 – spandana 2011-05-30 09:05:37

+0

嗨,阿爾文,很高興知道。請參閱「獲取運行時異常」:-) – 2011-05-30 09:43:42

0

我相信你的工作線程選擇器應該只有一個參數。

相關問題