自定义NSOperation并发的问题

rollrock1987 2015-12-09 04:10:58
想自己动手并发一个NSOperation,但是问题好大。
实现代码如下

#import "NSOperationA.h"

@interface NSOperationA()
{
BOOL isfihish;
BOOL isexcuting;
}
@end

@implementation NSOperationA

-(BOOL)isConcurrent{
return YES;
}
-(BOOL)isExecuting{
NSLog(@"isExecuting:%d",isexcuting);
return isexcuting;
}

-(BOOL)isFinished{
NSLog(@"isFinished:%d",isfihish);
return isfihish;
}

-(void)start{
if( [self isCancelled] ){
[self willChangeValueForKey:@"isFinished"];
isfihish = YES;
[self didChangeValueForKey:@"isFinished"];

NSLog(@"start- isCancelled");
}
else{
[self willChangeValueForKey:@"isExecuting"];
isexcuting = YES;
[self runLoop];
[self didChangeValueForKey:@"isExecuting"];
}
}

-(void)cancelSelf{
[self willChangeValueForKey:@"isFinished"];
isfihish = YES;
[self didChangeValueForKey:@"isFinished"];
}

-(void)runLoop{
while (![self isCancelled]) {
NSLog(@"runLoop");

[NSThread sleepForTimeInterval:1];
}
NSLog(@"runloop is canceled");
}

@end


调用代码如下:


//
NSOperationA*a;
////
a = [[NSOperationA alloc]init];
NSOperationQueue * q = [[NSOperationQueue alloc]init];
[q addOperation:a];
[self performSelector:@selector(cancelA) withObject:nil afterDelay:3];

//
-(void)cancelA
{
[a cancelSelf];
}

问题来了:
上面的代码打出来的log是这样的:
runloop
runloop
runloop
isFinished:1
runloop
runloop
N个runloop。

请问
1.为什么没有频繁的调用isFinished 跟isExecuting
2.为什么明明调用了cancelSelf,但是[self isCancelled] 依然是0.

如果将 [self runloop] 修改为[NSThread detachNewThreadSelector:@selector(runLoop) toTarget:self withObject:nil];
log如下:
runLoop
isExecuting:1
isFinished:0
runLoop
runLoop
isFinished:1
runLoop
runLoop
runLoop

问题:
1.为何这里会多了几次 isExecuting 跟 isFiished的调用?
...全文
163 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
Bannings 2015-12-10
  • 打赏
  • 举报
回复
你要达到什么效果?

29,027

社区成员

发帖
与我相关
我的任务
社区描述
主要讨论与iOS相关的软件和技术
社区管理员
  • iOS
  • 大熊猫侯佩
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧