Algorithm

lamport clock

The Lamport timestamp algorithm is a simple logical clock algorithm used to determine the order of events in a distributed computer system.

  1. a process increments its counter before each local event
  2. when a process sends a message, it includes its counter value with the message after executing step 1
  3. on receiving a message, the couner of the recipient is updated, if necessary, to the greater of its current counter and the timestamp in the received message. The counter is then incremented by 1 before the message is considered received.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class LamportClock:
    def __init__(self):
        self.time = 0

    def increment(self):
        """Increment the clock by 1 for local events."""
        self.time += 1

    def send_event(self):
        """Increment the clock for a send event."""
        self.increment()
        return self.time

    def receive_event(self, received_time):
        """Adjust the clock based on the received time from another process."""
        self.time = max(self.time, received_time) + 1

    def __str__(self):
        return str(self.time)

references

Licensed under CC BY-NC-SA 4.0
Get Things Done
Built with Hugo
Theme Stack designed by Jimmy