Concurrency overview
By default, when you make an application it runs the code in a single-thread environment, a main thread. For example, an iOS application would call the application:
didFinishLaunchingWithOptions
method on the main thread.
A simpler example is an OS X Command Line Tool application. It has only one file: main.swift
. When you start it, the system creates a single main thread and runs all the code in the main.swift
file on that thread.
For testing code, playgrounds are the best. By default, playgrounds stop after executing the last line of code and don't wait for the concurrent code to finish executing. We can change this behavior by telling the playgrounds to keep running indefinitely. To do that, include these two lines in the playground file:
import XCPlayground XCPSetExecutionShouldContinueIndefinitely()
Now we can start playing with concurrency. The first task we need to do to run code concurrently is to schedule a task to be run on a different thread. We can schedule a...