为什么我的后台线程没有运行?

时间:2011-05-30 06:41:41

标签: objective-c

doBackgroundWork方法不会从“开始工作”方法开始调用。

 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;
    }

detachNewThreadselector:toTarget:调试时不会调用withObject方法。

2 个答案:

答案 0 :(得分:3)

难道你的主要结局是后台线程无法启动吗?你知道,甚至在运行时设置并启动新线程之前,应用程序就完成了,并且所有线程都被杀死/关闭/等等。您可以让主线程休眠一秒钟以查看后台线程是否开始运行。

答案 1 :(得分:0)

你的工作线程选择器应该采用我认为的一个参数。