x
Loading
 Loading
Hello, Guest | Login | Register

Threads and Mutexes — Part II

Welcome to the second part of our look at programming with threads. In last month’s column we talked about the functions that allow you to create and wait on threads. This month we’re going to dive deeper into the problems that often arise when using threads to write concurrent programs. Before we begin that however, we’ll return to the ticket agent example we looked at last month and discuss the solution to the problem of over-selling of tickets.

Welcome to the second part of our look at programming with threads. In last month’s column we talked about the functions that allow you to create and wait on threads. This month we’re going to dive deeper into the problems that often arise when using threads to write concurrent programs. Before we begin that however, we’ll return to the ticket agent example we looked at last month and discuss the solution to the problem of over-selling of tickets.

One quick note before we proceed: If you’re writing applications that use the pthreads libraries for Linux, you must include the option -lpthread as a flag to the compiler on the command line. This will tell the compiler and linker to look for the necessary functions in the pthreads library and link them into your application.

The Ticket Agency

As we saw last month, using threads allows you to have multiple pieces of code that share and operate on a common set of data. However, threads introduce additional complexity and create code that is often difficult to debug. Let’s return to our ticket agency example. Each ticket agent may be thought of as one thread. There is common data between the ticket agents — the number of tickets to be sold. Our goal is to sell all the tickets without selling too many. Each ticket agent can be modeled with the C function:

void* ticket_agent (void* foo) { while (total_sold < NUM_TICKETS) {…

Please log in to view this content.

Not Yet a Member?

Register with LinuxMagazine.com and get free access to the entire archive, including:

  • Hands-on Content
  • White Papers
  • Community Features
  • And more.
Already a Member?
Log in!
Username

Password

Remember me

Forgotten your password?
Forgotten your username?
Read More
  1. Helpful Tools for Software Developers
  2. The Github Hall of Fame
  3. Book'em, Github.
  4. This Week on Github: Stupid Ruby Tricks
  5. A Veritable Scatter Shot!
Follow Linux Magazine
Rackspace