Search code examples
multithreadingalgorithmconcurrencyoperating-systemraku

Where is Peterson's algorithm used in the real world?


I'm reading Operating Systems: Three Easy Pieces and I understand Peterson's algorithm is a synchronization mechanism that provides mutual exclusion among processes/threads, however it's unclear to me whether the algorithm underlies the implementation of concurrent constructs in any programming language. Take, for example, this Raku snippet with its critical section, i.e., $counter += 1, protected by using the Lock construct:

my UInt:D $counter = 0;
my Lock:D $lock = Lock.new;

my Thread:D $t0 = Thread.start({
    for 1..1000 {
        $lock.protect({ $counter += 1 });
    }
});

my Thread:D $t1 = Thread.start({
    for 1..1000 {
        $lock.protect({ $counter += 1 });
    }
});

$t0.finish;
$t1.finish;

say "Counter: $counter";

Assuming that I understand the shortcomings/cons of Peterson's algorithm, could I swap out Raku's Lock with Peterson's algorithm and still have a working program with a protected critical section?

In conclusion, is Peterson's algorithm simply a pedagogical exercise? What's its relation to mutexes, for example? Could it be potentially used in production code (again assuming that I know what I'm doing)?


Solution

  • Early computer systems didn't have any instructions to perform operations like atomic test-and-set, much less atomic exchange, atomic increment/decrement with test, or (especially) atomic compare-exchange or load-linked/store-conditional. Adding atomic operations makes managing a mutex trivial, since one can have an arbitrary number of tasks use:

    if (!test_and_set(&task_busy))
    {
      ... do task
      task_busy = 0;
    }
    else
      ... do_something else for awhile and try again later
    

    On the flip side, the Peterson algorithm assumes that if task #1 writes X and then Y, and task #2 reads Y and then X, it's not possible for task #2 to read the new value of Y but then read the old value of X, but upholding that guarantee on some of today's systems can be quite expensive. The cost of each step in the Peterson algorithm has increased to the point that their total cost significantly exceeds the cost of a test-and-set, compare-exchange, or similar operation.