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:
我有一个基于代理的小型建模框架,我正在写作项目的一部分。不同的代理都在自己的线程中运行,而主管类控制着它们的生命周期。因此,主管类可以取消这些线程。我知道NSThread上有一个isCancelled方法。使用它,可以接受以下习语:
#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
}
}
1 个解决方案
#1
3
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.
如果您的线程支持取消,它应该定期调用此方法,如果它返回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.
不过,我建议你看看NSOperation和NSOperationQueue。它们旨在允许您在代表您管理实际线程时实现这种并发性。请参阅“并发编程指南”中的“操作队列”。
#1
3
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.
如果您的线程支持取消,它应该定期调用此方法,如果它返回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.
不过,我建议你看看NSOperation和NSOperationQueue。它们旨在允许您在代表您管理实际线程时实现这种并发性。请参阅“并发编程指南”中的“操作队列”。