Low-level details of the implementation of performSelectorOnMainThread:

后端 未结 4 1497
情歌与酒
情歌与酒 2021-02-06 07:13

Was wondering if anyone knows, or has pointers to good documentation that discusses, the low-level implementation details of Cocoa\'s \'performSelectorOnMainThread:\' method.

4条回答
  •  天涯浪人
    2021-02-06 07:33

    Yes, it does use Mach ports. What happens is this:

    1. A block of data encapsulating the perform info (the target object, the selector, the optional object argument to the selector, etc.) is enqueued in the thread's run loop info. This is done using @synchronized, which ultimately uses pthread_mutex_lock.
    2. CFRunLoopSourceSignal is called to signal that the source is ready to fire.
    3. CFRunLoopWakeUp is called to let the main thread's run loop know it's time to wake up. This is done using mach_msg.

    From the Apple docs:

    Version 1 sources are managed by the run loop and kernel. These sources use Mach ports to signal when the sources are ready to fire. A source is automatically signaled by the kernel when a message arrives on the source’s Mach port. The contents of the message are given to the source to process when the source is fired. The run loop sources for CFMachPort and CFMessagePort are currently implemented as version 1 sources.

    I'm looking at a stack trace right now, and this is what it shows:

    0 mach_msg
    1 CFRunLoopWakeUp
    2 -[NSThread _nq:]
    3 -[NSObject(NSThreadPerformAdditions) performSelector:onThread:withObject:waitUntilDone:modes:]
    4 -[NSObject(NSThreadPerformAdditions) performSelectorOnMainThread:withObject:waitUntilDone:]
    

    Set a breakpoint on mach_msg and you'll be able to confirm it.

提交回复
热议问题