[英]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
. 我知道,有一个
isCancelled
的方法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 : 我会这么说,因为这在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. 但我建议您看看
NSOperation
和NSOperationQueue
。 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.
请参见《并发编程指南》中的“操作队列” 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.