我正在编写一个简单的应用程序,它应该能够使用 Apple 的 CoreFoundation 框架在后台线程中接收和处理通知。这是我要完成的工作:
static void DummyCallback(CFNotificationCenterRef center,
void *observer,
CFStringRef name,
const void *object,
CFDictionaryRef userInfo) {
printf("RECEIVED NOTIFICATION\n");
}
void *ThreadStart(void *arg) {
CFNotificationCenterAddObserver(CFNotificationCenterGetDistributedCenter(),
NULL,
&DummyCallback,
NULL,
CFSTR("TEST_OBJECT"),
CFNotificationSuspensionBehaviorDeliverImmediately);
printf("background thread: run run loop (should take 5 sec to exit)\n");
int retval = CFRunLoopRunInMode(kCFRunLoopDefaultMode, 5, true);
printf("background thread: exited from run loop (retval: %d)\n", retval);
return NULL;
}
int main(int argc, char** argv) {
pthread_t thread;
int rc = pthread_create(&thread, NULL, &ThreadStart, NULL);
assert(rc == 0);
printf("main: sleep\n");
sleep(10);
printf("main: done sleeping\n");
return 0;
}
如果我运行程序,我会得到
main: sleep
background thread: run run loop (should take 5 sec to exit)
background thread: exited from run loop (retval: 1)
main: done sleeping
问题是后台线程的运行循环立即退出(返回代码 kCFRunLoopRunFinished 而不是 kCFRunLoopRunTimedOut),因为没有源/观察者/计时器。CFNotificationCenterAddObserver 只在主线程的运行循环中注册自己,而不是我的后台线程之一。
我需要一些其他东西的主线程并且不能使用它来运行它的运行循环。有什么办法可以让这个工作吗?也许通过在后台线程的运行循环中注册 CFNotificationCenter ?
提前致谢!