Chapter 16. Multiprocessing with Threads

In This Chapter

  • Understanding the causes of thread errors

  • Learning how to prevent thread errors with locks

  • Using @synchronize

  • Creating threads with NSThread

  • Using NSOperation and NSOperationQueue

Threads. Probably no other computing subject strikes more fear and trepidation into the hearts of experienced programmers. It should. Threads cause bugs that are difficult to track down, difficult to reproduce, and maddeningly frustrating to fix. At the same time, however, they promise to unlock more of our multi-core computing potential than any other modern software technology. This dual nature makes them a complex subject worthy of an entire chapter dedicated to handling them properly.

Every program has at least one thread, usually called the main thread. The main thread begins execution in your main function and then is responsible for executing the rest of your application code unless you explicitly create another thread.

Conceptually, you can think of a thread as a single line of execution through your application by which instructions are executed sequentially. When you create another thread, you actually have two separate threads of execution, running through your application in parallel. If your application is running on a single core, single CPU machine, your threads may appear to be running simultaneously, however, they are actually given different time slices on the CPU. On the other hand, if your application is running on a multicore, or multi-CPU ...

Get Objective-C 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.