基本上,我的任务非常简单 - 我有一个名为SomeBigSingletonClass的大型单例类,它有两个方法someMethodOne和someMethodTwo。这些方法应该定期(基于定时器)在不同的线程中调用。但是,在任何时候都只应该有一个实例的每个线程,例如,每次只应该运行一个someMethodOne方法,对于someMethodTwo也是如此。
我尝试过使用GCD进行实现,但它缺少非常重要的功能,即它不能提供检查当前是否有正在运行的任务的手段,例如,我无法检查是否只有一个running instance of let say someMethodOne方法。
NSThread提供了良好的功能,但我相信像NSOperation和GCD这样的新高级技术将使维护我的代码更加简单。所以我决定放弃NSThread。
我的解决方案是使用NSOperation: 我计划如何实现这两个线程调用。
@implementation SomeBigSingletonClass
- (id)init
{
...
// queue is an iVar
queue = [[NSOperationQueue alloc] init];
// As I'll have maximum two running threads
[queue setMaxConcurrentOperationCount:2];
...
}
+ (SomeBigSingletonClass *)sharedInstance
{
static SomeBigSingletonClass *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[SomeBigSingletonClass alloc] init];
});
return sharedInstance;
}
- (void)someMethodOne
{
SomeMethodOneOperation *one = [[SomeMethodOneOperation alloc] init];
[queue addOperation:one];
}
- (void)someMethodTwo
{
SomeMethodTwoOperation *two = [[SomeMethodOneOperation alloc] init];
[queue addOperation:two];
}
@end
最后,我的NSOperation继承类将如下所示。
@implementation SomeMethodOneOperation
- (id)init
{
if (![super init]) return nil;
return self;
}
- (void)main {
// Check if the operation is not running
if (![self isExecuting]) {
[[SomeBigSingletonClass sharedInstance] doMethodOneStuff];
}
}
@end
同样适用于 SomeMethodTwoOperation 操作类。