Book Image

Extreme C

By : Kamran Amini
5 (1)
Book Image

Extreme C

5 (1)
By: Kamran Amini

Overview of this book

There’s a lot more to C than knowing the language syntax. The industry looks for developers with a rigorous, scientific understanding of the principles and practices. Extreme C will teach you to use C’s advanced low-level power to write effective, efficient systems. This intensive, practical guide will help you become an expert C programmer. Building on your existing C knowledge, you will master preprocessor directives, macros, conditional compilation, pointers, and much more. You will gain new insight into algorithm design, functions, and structures. You will discover how C helps you squeeze maximum performance out of critical, resource-constrained applications. C still plays a critical role in 21st-century programming, remaining the core language for precision engineering, aviations, space research, and more. This book shows how C works with Unix, how to implement OO principles in C, and fully covers multi-processing. In Extreme C, Amini encourages you to think, question, apply, and experiment for yourself. The book is essential for anybody who wants to take their C to the next level.
Table of Contents (23 chapters)

Spin locks

Before starting to talk about the condition variables and the true way that the sleep/notify technique should get implemented, let's go back a little bit and use busy-waiting together with mutexes to write a new solution for example 14.6. As a reminder, the example was about having first A and then B printed in the standard output.

The following is the proposed solution that uses a mutex equipped with the spin locking algorithm. The mutex acts as a memory barrier, so we won't have any memory visibility issues, and it effectively synchronizes the tasks P and Q over the Done shared flag:

Concurrent System {
  Shared State {
      Done : Boolean = False
      M : Mutex
  Task P {
      1.1. print 'A'
      1.2. SpinLock(M)
      1.2. Done = True
      1.3. SpinUnlock(M)
  Task Q {
      2.1  SpinLock(M)
      2.2. While Not Done {
      2.3.   SpinUnlock(M)
      2.4.   SpinLock(M)
      2.5. }
      2.6. SpinUnlock(M)
      2.4. print...