您可以使用运行循环源。在本质上:
1)在辅助工作线程上创建并安装运行循环源,并以某种方式将其与工作线程运行循环引用一起传递给将向该线程发送消息的其他管理线程:
CFRunLoopSourceContext context = {0, self, NULL, NULL, NULL, NULL, NULL,
&RunLoopSourceScheduleRoutine,
RunLoopSourceCancelRoutine,
RunLoopSourcePerformRoutine};
CFRunLoopSourceRef runLoopSource = CFRunLoopSourceCreate(NULL, 0, &context);
CFRunLoopRef runLoop = CFRunLoopGetCurrent();
CFRunLoopAddSource(runLoop, runLoopSource, kCFRunLoopDefaultMode);
// Pass runLoopSource and runLoop to managing thread
这里有上面提到的自定义例程 - 您有责任提供它们:
RunLoopSourceScheduleRoutine - called when you install run loop source (more precisely, when you call CFRunLoopAddSource)
RunLoopSourceCancelRoutine - called when you remove run loop source (more precisely, when you call CFRunLoopSourceInvalidate)
RunLoopSourcePerformRoutine - called when run loop source was signaled (received a message from manager thread) and this is a place where you should perform a job
2)在工作线程上,启动通常的运行循环,类似于以下内容:
BOOL done = NO;
do {
int result = CFRunLoopRunInMode(kCFRunLoopDefaultMode, 10, YES);
done = (result == kCFRunLoopRunStopped) || (result == kCFRunLoopRunFinished);
} while (!done);
3)现在,在管理线程时,您可以在需要时向先前接收到的运行循环源发出信号(发送消息)(并唤醒那些线程的运行循环以防它处于睡眠状态):
CFRunLoopSourceSignal(runLoopSource);
CFRunLoopWakeUp(workerThreadRunLoop);
更多细节在 Apple 的指南中。