3

我有一个似乎CFRunLoopWakeUp不起作用的案例。这是设置:

我有一个“典型的”while循环不在等待一些工作完成的主线程上:

- (void)someFunc
{
    self.runLoop = CFRunLoopGetCurrent();
    NSLog(@"Pre loop.");
    while (!self.completed)
    {
        NSLog(@"In loop.");
        NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
        [pool release];
    }
    NSLog(@"Post loop.");
}

我有一个回调函数等待某些工作完成。这也不是从主线程调用的:

- (void)callback
{
    NSLog(@"Work completed.");
    self.completed = YES;

    // I've checked that CFRunLoopIsWaiting(self.runLoop) here returns true
    CFRunLoopWakeUp(self.runLoop); // Should wake up the waiting run loop, but doesn't!
}

回调被调用,但由于某种原因,CFRunLoopWakeUp似乎没有做任何事情。我错过了一些明显的东西吗?这里有一些深线程问题吗?谢谢!

4

2 回答 2

0

首先,我无法重现您的问题。我正在像这样在 GCD 中构建它:

int main (int argc, const char *argv[])
{
  @autoreleasepool {
    __block BOOL completed = NO;
    __block CFRunLoopRef runLoop;

    dispatch_queue_t queue1 = dispatch_queue_create("first", 0);
    dispatch_queue_t queue2 = dispatch_queue_create("second", 0);

    dispatch_async(queue1, ^{
      runLoop = CFRunLoopGetCurrent();
      NSLog(@"Pre loop.");
      while (!completed)
      {
        NSLog(@"In loop.");
        @autoreleasepool {
          [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
        }
      }
      NSLog(@"Post loop.");
    });

    double delayInSeconds = 2.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (unsigned)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, queue2, ^(void) {
      NSLog(@"Work completed.");
      completed = YES;

      // I've checked that CFRunLoopIsWaiting(self.runLoop) here returns true
      CFRunLoopWakeUp(runLoop); // Should wake up the waiting run loop, but doesn't!

    });

    dispatch_sync(queue1, ^{});
    dispatch_sync(queue2, ^{});
    dispatch_release(queue1);
    dispatch_release(queue2);
  }
  return 0;
}

你能建立一个更简单的程序来演示这个问题吗?

我会尝试的其他事情,主要用于调试目的以缩小问题范围:

  • 切换到CFRunLoopRunInMode()而不是runinMode:beforeDate:. 它们略有不同。
  • 切换到CFRunLoopStop()而不是CFRunLoopWakeUp().

当然,请确保它self.runLoop实际上指向您认为的运行循环!

于 2012-06-28T05:06:58.510 回答
-1

正如这个人解释的那样,我可以通过添加一个源来使 CFRunLoopWakeUp 工作:http: //www.cocoabuilder.com/archive/cocoa/112261-cfrunlooptimer-firing-delay.html

于 2012-06-26T18:24:18.067 回答