Handling asynchronous closures

Modern operating environments are multi-threaded. This means work can happen simultaneously on multiple threads of execution. For example, all networking operations execute in a background thread so they don’t block the user interface that happens on the main thread. In practice, working in multi-threaded environments can be very tricky. For example, just as one thread is writing some

data, another thread might be trying to read it and get a half-baked value but only very occasionally making it very difficult to diagnose.

In order to avoid race conditions like this, synchronization becomes necessary. Although Swift does not yet have a native concurrency model, you can use a framework called Grand Central Dispatch or GCD to simplify many of these issues. GCD is an abstraction on top of threads that makes doing background work less error prone.

Note: Swift initialization of global data and reference counting are thread safe so you don't need to worry about those fundamental things.

Since GCD lets you pass around closures and those closures may contain references to objects, you need to be aware of what is getting passed around so as not to create unintended cycles. The ownership principles discussed earlier exactly the same as synchronous code. The danger comes that since the order of completion changes from run to run, you need to be extra careful not to access an unowned reference that may have disappeared.

results matching ""

    No results matching ""