Book Image

The Art of Writing Efficient Programs

By : Fedor G. Pikus
3 (2)
Book Image

The Art of Writing Efficient Programs

3 (2)
By: Fedor G. Pikus

Overview of this book

The great free lunch of "performance taking care of itself" is over. Until recently, programs got faster by themselves as CPUs were upgraded, but that doesn't happen anymore. The clock frequency of new processors has almost peaked, and while new architectures provide small improvements to existing programs, this only helps slightly. To write efficient software, you now have to know how to program by making good use of the available computing resources, and this book will teach you how to do that. The Art of Efficient Programming covers all the major aspects of writing efficient programs, such as using CPU resources and memory efficiently, avoiding unnecessary computations, measuring performance, and how to put concurrency and multithreading to good use. You'll also learn about compiler optimizations and how to use the programming language (C++) more efficiently. Finally, you'll understand how design decisions impact performance. By the end of this book, you'll not only have enough knowledge of processors and compilers to write efficient programs, but you'll also be able to understand which techniques to use and what to measure while improving performance. At its core, this book is about learning how to learn.
Table of Contents (18 chapters)
1
Section 1 – Performance Fundamentals
7
Section 2 – Advanced Concurrency
11
Section 3 – Designing and Coding High-Performance Programs

The thread-safe queue

The next data structure we are going to consider is the queue. It is again a very simple data structure, conceptually an array that is accessible from both ends: the data is added to the end of the array and removed from the beginning of it. There are some very important differences between the queue and the stack when it comes to implementation. There are also many similarities, and we will refer to the previous section frequently.

Just like the stack, the STL has a queue container, std::queue, and it has the exact same problem when it comes to concurrency: the interface for removing elements is not transactional, it requires three separate member function calls. If we wanted to use std::queue with a lock to create a thread-safe queue, we would have to wrap it just like we did with the stack:

03_queue.C

template <typename T> class mt_queue {
  std::queue<T> s_;
  mutable spinlock l_;
  public:
  void...