为什么NSOperation在没有做任何事情时会使用100%的CPU周期?

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%.这就是循环所做的事情,无论是否在队列中.

  • 正确,第二个while循环没有被执行,因为你的运行循环是. (5认同)
  • v01d:不仅直到它触发,而且直到它失效(从运行循环中删除).只要它有效,运行循环将继续运行,并且重复计时器有效,直到您明确使其无效. (2认同)