Is there any guide for iOS runloop mechanism?

2019-02-01 01:41发布

问题:

I'm learning socket communication on iPhone, and its guide said something about CFRunloop(it is a guide for CFNetwork, can this be used on iOS?) Where can I learn about runloop on iOS?API reference is not enough.

回答1:

Look at the "Run Loops" chapter of Apple's Threading Programming Guide. In brief:

  • There is one run loop associated with each thread.
  • The run loop has to be run to do anything. Apple's application main function takes care of this for you on the main thread.
  • A run loop is run in a specific mode. The "common mode" is actually a set of modes, and there is an API for adding modes to that set.
  • A run loop's main purpose is to monitor timers and run loop sources. Each source is registered with a specific run loop for a specific mode, and will only be checked at the appropriate time when the runloop is running in that mode.
  • The run loop goes through several stages in each go around its loop, such as checking timers and checking other event sources. If it finds that any source is ready to fire, it triggers the appropriate callback.
  • Aside from using ready-made run loop tools, you can create your own run loop sources as well as registering a run loop observer to track the progress of the run loop.

One major pitfall is forgetting to run the run loop while waiting for a callback from a runloop source. This is sometimes a problem when you decide to busy-wait for something to happen on the main thread, but you're most likely to run into it when you create your own thread and register a runloop source with that runloop. You are responsible for establishing an autorelease pool and running the runloop if needed on non-main threads, since the application main function will not be there to do it for you.

You would do better to read Apple's Concurrency Programming Guide instead, which suggests alternatives to the runloop mechanism such as operation queues and dispatch sources. The "Replacing Run-Loop Code" section of the "Migrating Away from Threads" chapter suggests using dispatch sources instead of runloop sources to handle events.



回答2:

Have a look at these articles in the Apple docs:

Main event loop

Run Loops

For sample code on how to run asynchronous connections via the run loop:

SimpleURLConnections (although this one uses the NSURLConnection API)



回答3:

NSRunLoop is an Event-Driven-Mode(android Handler-Looper-MessageQueue and memcached etc)

We use pipe() to generate two fd(one for read, another for write). We can wakeup the thread (who read the read fd) by writing some bytes to write fd in other thread.

This project(sponsor by me) can give you more information.

https://github.com/wuyunfeng/LightWeightRunLoop

I believe this project can help you understand iOS/Mas Runloop clearly and sufficiently, so you can design your project by using runloop correctly and effectively.

Hope this can help you.