Logical time: Lamport clocks

In a distributed system each machine has its own physical clock, and those clocks drift apart, so timestamps from different machines cannot be trusted to order events. Leslie Lamport's 1978 paper replaced wall-clock time with logical time based on causality. The happened-before relation, written →, says that event a happened before b if they occur in that order in the same process, or if a is the sending of a message and b is its receipt, or if the two are linked by a chain of such steps. Events not related this way are concurrent.

Python
class Process:
    def __init__(self, name):
        self.name = name
        self.clock = 0

    def local_event(self):
        self.clock += 1
        return self.clock

    def send(self):
        self.clock += 1
        return self.clock

    def receive(self, timestamp):
        self.clock = max(self.clock, timestamp) + 1
        return self.clock


a = Process("A")
b = Process("B")
a.local_event()
sent = a.send()
b.local_event()
received = b.receive(sent)
print(sent, received)
print(received > sent)
print(a.clock, b.clock)
Read the full lesson