简体   繁体   中英

Is this an acceptable idiom for NSThread in Objective-C?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM