A Deep Chasm Opens Before You

While multithreading can be essential in certain applications, it also opens up an entirely new category of bugs that are notoriously difficult to fix: race conditions. It is for this reason that we suggest that you carefully weigh the benefits of multithreading against the significant costs.

Race conditions occur when code is modifying the same data in two or more threads. Consider the classic case of two threads incrementing a global variable (Figure 34.1). Here is the global integer variable:

v​a​r​ ​g​l​o​b​a​l​C​o​u​n​t​ ​=​ ​0​

Figure 34.1  A classic race condition

A classic race condition

Now imagine the two ...

Get Cocoa Programming for OS X: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.