2011-05-30 80 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

我相信你的工作线程选择器应该只有一个参数。

相关问题