Почему не запускается мой фоновый поток? - PullRequest
1 голос
/ 30 мая 2011

Метод 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 не вызывается при отладке.

Ответы [ 2 ]

3 голосов
/ 30 мая 2011

Не правда ли, что ваш основной заканчивается так быстро, что фоновый поток не имеет шансов на запуск?Вы знаете, прежде чем даже среде выполнения удастся настроить и запустить новый поток, приложение завершится, и все потоки будут уничтожены / закрыты / что угодно.Вы можете перевести основной поток в спящий режим на секунду, чтобы проверить, запускаются ли фоновые потоки.

0 голосов
/ 30 мая 2011

Ваш селектор рабочих потоков должен принимать ровно один аргумент.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...