Dav*_*vid 2 cocoa multithreading objective-c nsoperation
我刚刚遇到NSOperation的一个奇怪的行为,我修复但不明白.
我按照文档继承了NSOperation.当我使用下面的main方法时,应用程序将使用100%或更多的CPU时间.
-(void)main
{
@try
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
//Cycle forever until told to cancel
while (![self isCancelled])
{
}
[pool release];
}
@catch(...)
{
// Do not rethrow exceptions.
}
//Finish executing
[self completeOperation]; //Send notificatios using KVO
}
Run Code Online (Sandbox Code Playgroud)
相反,当我使用以下主方法时,应用程序使用3%的CPU时间.
-(void)main
{
@try
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
//Create the initial delayed timers
NSTimer *startUpTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
[runLoop addTimer:startUpTimer forMode:NSRunLoopCommonModes];
[runLoop run];
//Cycle forever until told to cancel
while (![self isCancelled])
{
}
[pool release];
}
@catch(...)
{
// Do not rethrow exceptions.
}
//Finish executing
[self completeOperation]; //Send notificatios using KVO
}
Run Code Online (Sandbox Code Playgroud)
这种奇怪的行为似乎归因于计时器.如果要求计时器不重复,则应用程序使用100%CPU时间,但如果要求计时器重复,则CPU使用率正常.
似乎当线程上没有运行时,CPU使用率非常高(我认为它会相反).为什么会出现这种情况的任何建议?
谢谢.
v01*_*01d 14
循环一段时间循环将占用CPU的单个核心的100%.这就是循环所做的事情,无论是否在队列中.
| 归档时间: |
|
| 查看次数: |
1315 次 |
| 最近记录: |