Clarification on Threads and Run Loops In Cocoa

后端 未结 2 392
花落未央
花落未央 2021-02-03 11:30

I\'m trying to learn about threading and I\'m thoroughly confused. I\'m sure all the answers are there in the apple docs but I just found it really hard to breakdown and digest.

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-03 11:59

    Run Loops

    You can think of a Run Loop to be an event processing for-loop associated to a thread. This is provided by the system for every thread, but it's only run automatically for the main thread.

    Note that running run loops and executing a thread are two distinct concepts. You can execute a thread without running a run loop, when you're just performing long calculations and you don't have to respond to various events. If you want to respond to various events from a secondary thread, you retrieve the run loop associated to the thread by

    [NSRunLoop currentRunLoop]
    

    and run it. The events run loops can handle is called input sources. You can add input sources to a run-loop.

    PerformSelector

    performSelectorOnMainThread: adds the target and the selector to a special input source called performSelector input source. The run loop of the main thread dequeues that input source and handles the method call one by one, as part of its event processing loop.

    NSOperation/NSOperationQueue

    I think of NSOperation as a way to explicitly declare various tasks inside an app which takes some time but can be run mostly independently. It's easier to use than to detach the new thread yourself and maintain various things yourself, too. The main NSOperationQueue automatically maintains a set of background threads which it reuses, and run NSOperations in parallel. So yes, if you just need to queue up operations in the main thread, you can do away with NSOperationQueue and just use performSelectorOnMainThread:, but that's not the main point of NSOperation.

    GCD

    GCD is a new infrastructure introduced in Snow Leopard. NSOperationQueue is now implemented on top of it. It works at the level of functions / blocks. Feeding blocks to dispatch_async is extremely handy, but for a larger chunk of operations I prefer to use NSOperation, especially when that chunk is used from various places in an app.

    Summary

    You need to read Official Apple Doc! There are many informative blog posts on this point, too.

提交回复
热议问题