Frage

I have a small agent-based modeling-framework that I'm writing as part of a project. The different agents all run in their own threads and a supervisor class controls their lifecycles. So the supervisor class can cancel these threads. I know that there is an isCancelled method on NSThread. Using that, is the following idiom acceptable:

#import <Foundation/Foundation.h>
#import "BugThread.h"
#import "Bug.h"

@implementation BugThread

- (id) initWithBug: (Bug*) aBug {

    if((self = [super init])) {
        [bug autorelease];
        bug = [aBug retain];
    }

    return self;
}

- (void) main {

    GSRegisterCurrentThread();

    while(![self isCancelled]) {
        //bug does its stuff
    }
}
War es hilfreich?

Lösung

I would say so, since this is explicitly stated in the docs:

If your thread supports cancellation, it should call this method periodically and exit if it ever returns YES.

I'd recommend that you take a look at NSOperation and NSOperationQueue, though. They're intended to allow exactly this kind of concurrency while managing the actual threads on your behalf. See "Operation Queues" in the Concurrency Programming Guide.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top