Introduction
并发表示多个事情在同一时间发生。伴随着多核CPU的增多和每个处理器的核的数量的上升,软件开发需要新的途径来利用这些优势。虽然像OS X and iOS这些操作系统有能力并发运行多个程序,大部分运行在后台的程序只需要少量连续的处理时间。是当前前台程序捕捉用户事件让处理器保持忙碌。如果一个程序有很多的工作但全让一个核来做,其他的处理资源就被浪费掉了。
在以前,在一个app中引进并发需要创建一个或多个额外的threads。不幸的是,编写threaded code是一件很有挑战的事。Threads是一个底层的工具,必须手动管理。根据当前系统和底层硬件来动态选择更优的线程数目,实现一个正确的线程解决方案是一件极度困难的事,几乎不可能达到。另外,同步机制增添了软件的复杂性和风险,且并不能保证提升性能。
OS X and iOS都适配了更异步的方法来执行并发任务。不同于直接创建threads,app只需要定义任务并让系统执行它们。通过让系统管理线程,app获得了一层不使用裸线程的伸缩性。同时开发者也获得一个更简单和高效的编程模型。
This document describes the technique and technologies you should be using to implement concurrency in your applications. The technologies described in this document are available in both OS X and iOS.
Organization of This Document
This document contains the following chapters:
Concurrency and Application Design introduces the basics of asynchronous application design and the technologies for performing your custom tasks asynchronously.
Operation Queues shows you how to encapsulate and perform tasks using Objective-C objects.
Dispatch Queues shows you how to execute tasks concurrently in C-based applications.
Dispatch Sources shows you how to handle system events asynchronously.
Migrating Away from Threads provides tips and techniques for migrating your existing thread-based code over to use newer technologies.
This document also includes a glossary that defines relevant terms.
A Note About Terminology
Before entering into a discussion about concurrency, it is necessary to define some relevant terminology to prevent confusion. Developers who are more familiar with UNIX systems or older OS X technologies may find the terms “task”, “process”, and “thread” used somewhat differently in this document. This document uses these terms in the following way:
The term thread is used to refer to a separate path of execution for code. The underlying implementation for threads in OS X is based on the POSIX threads API.
The term process is used to refer to a running executable, which can encompass multiple threads.
The term task is used to refer to the abstract concept of work that needs to be performed.
For complete definitions of these and other key terms used by this document, see Glossary.