ios queue及GCD理解的文章

来源:互联网 发布:apache2 php 编辑:程序博客网 时间:2024/06/08 08:12

(1)关于queue

The best way to conceptualize queues is to first realize that at the very low-level, there are only two types of queues: serial and concurrent.

Serial queues are monogamous, but uncommitted. If you give a bunch of tasks to each serial queue, it will run them one at a time, using only one thread at a time. The uncommitted aspect is that serials queues may switch to a different thread between tasks. Serial queues always wait for a task to finish before going to the next one. Thus tasks are completed in FIFO order. You can make as many serial queues as you need.

The main queue is a special serial queue. Unlike other serial queues, which are uncommitted, in that they are "dating" many threads but only one at time, the main queue is "married" to the main thread and all tasks are performed on it. The main queue behaves nicely with the main thread's runloop so that small operations don't block the UI and other important bits. Like all serial queues, tasks are completed in FIFO order.

If serial queues are monogamous, concurrent queues are promiscuous. They will submit tasks to any available thread or even make new threads depending on system load. They may perform multiple tasks simultaneously on different threads. It's important that tasks submitted to the global queue are thread-safe and minimize side-effects. Tasks are submitted for execution in FIFO order, but order of completion is not guaranteed.

Bringing it back, all global queues are concurrent and all user queues are serial.

If your goal is to download images, you probably want a serial (user) queue. Downloading images is more of a bandwidth thing. You usually only want to do a one (or a few) at a time.


(2)GCD

https://www.raywenderlich.com/60749/grand-central-dispatch-in-depth-part-1

0 0