x
Loading
 Loading
Hello, Guest | Login | Register

Programming with Threads

Last month we looked at using pipes and FIFOs to communicate between concurrently running processes. However, there are occasions when you might want to run two pieces of code concurrently without the limitations of communicating through pipes. Perhaps you have two (or more) pieces of code that need to share a set of data or are constantly updating shared data structures. Pipes and FIFOs are not well-suited to handle this kind of situation because they would require each process to keep its own copy of the data and to communicate with all other processes when that data changes. Such an arrangement would cause a great deal of problems and would be very difficult to debug.

Last month we looked at using pipes and FIFOs to communicate between concurrently running processes. However, there are occasions when you might want to run two pieces of code concurrently without the limitations of communicating through pipes. Perhaps you have two (or more) pieces of code that need to share a set of data or are constantly updating shared data structures. Pipes and FIFOs are not well-suited to handle this kind of situation because they would require each process to keep its own copy of the data and to communicate with all other processes when that data changes. Such an arrangement would cause a great deal of problems and would be very difficult to debug.

Fortunately, Linux provides us with “threads,” a programming tool for handling situations like these. Threads allow two or more pieces of code that are running concurrently to share the same set of resources. In this article I will introduce threads and the basic functions of the pthreads library that are necessary to create multiple threads of execution in your applications.

Threads (sometimes referred to as “threads of execution”) differ from simultaneously running processes because they share the same pool of memory. Even if you have never explicitly programmed with threads before, all the programs you’ve written have implicitly contained a single thread (the thread that calls your main() function at the beginning of the program and exits when the code in main() is finished).

You can think of each new thread…

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