Cowboy Tech

Grand_Central_Dispatch_Tutorial_for_Swift1

Term

GCD is the marketing name for libdispatch

Serial vs. Concurrent

These terms describe when tasks are executed with respect to each other.

Tasks executed serially are always executed one at a time.

Tasks executed concurrently might be executed at the same time.

Synchronous vs. Asynchronous(同步和异步)

These terms describe when a function will return control to the caller, and how much work will have been done by that point.

A synchronous function returns only after the completion of a task that it orders.

An asynchronous function, on the other hand, returns immediately, ordering the task to be done but not waiting for it. Thus, an asynchronous function does not block the current thread of execution from proceeding on to the next function.

Critical Section

This is a piece of code that must not be executed concurrently, which might manipulates a shared resource

Race Condition

Deadlock

两个thread互相等待对方完成,陷入僵局

Thread Safe

Thread safe code can be safely called from multiple threads or concurrent tasks without causing any problems

设定常量是线程安全的,变量不一定安全,因为可能被其他线程的所改变值

Variables and data structures that are mutable and not inherently thread-safe should only be accessed from one thread at a time.

Context Switch

A context switch is the process of storing and restoring execution state when you switch between executing different threads on a single process.

Concurrency vs Parallelism

Multi-core devices execute multiple threads at the same time via parallelism

Single-cored devices must run a thread, perform a context switch

Parallelism requires concurrency, but concurrency does not guarantee parallelism.

Queues

GCD provides dispatch queues to handle submitted tasks; these queues manage the tasks you provide to GCD and execute those tasks in FIFO order

Serial Queues

executes only one task at a time

1

Concurrent Queues

The decision of when to start a task is entirely up to GCD.

2

Queue Types

You have at least five queues at your disposal: the main queue, four global dispatch queues, plus any custom queues

  • Main queue:which is the only thread allowed to update your UI.

  • QOS_CLASS_USER_INTERACTIVE

  • QOS_CLASS_USER_INITIATED

  • QOS_CLASS_UTILITY

  • QOS_CLASS_BACKGROUND