Chapter 12. Threads: It’s a parallel world

image with no caption

Programs often need to do several things at the same time.

POSIX threads can make your code more responsive by spinning off several pieces of code to run in parallel. But be careful! Threads are powerful tools, but you don’t want them crashing into each other. In this chapter, you’ll learn how to put up traffic signs and lane markers that will prevent a code pileup. By the end, you will know how to create POSIX threads and how to use synchronization mechanisms to protect the integrity of sensitive data.

Tasks are sequential...or not...

Imagine you are writing something complex like a game in C. The code will need to perform several different tasks:

image with no caption

Not only will your code need to do all of these things, but it will need to do them all at the same time. That’s going to be true for many different programs. Chat programs will need to read text from the network and send data to the network at the same time. Media players will need to stream video to the display as well as watch for input from the user controls.

How can your code perform several different tasks at once?

...and processes are not always the answer

You’ve already learned how to make the computer do several things at once: with processes. In the last chapter, you built a network ...

Get Head First 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.