Distributed & Networked Operating Systems

a Lamport clock

/ LAM-port /

If you cannot trust the wall clocks on different machines (and in a distributed system you cannot), how can you ever say one event happened before another? Leslie Lamport's clever answer was: stop trying to measure real time and instead just count, in a way that respects cause and effect. A Lamport clock is not a clock that tells the time — it is a simple counter on each machine that lets the whole system agree on the ORDER of events whenever order actually matters, without any synchronized physical time.

The rules are wonderfully simple. Each process keeps a counter starting at 0. (1) Before it does any local event, it adds 1 to its counter and stamps the event with that number. (2) When it sends a message, it attaches its current counter value. (3) When it receives a message, it sets its counter to the larger of its own value and the value in the message, then adds 1. The effect captures the happened-before relation: if event X could possibly have caused event Y — because they are on the same process in sequence, or because X sent a message that Y received — then X's timestamp is guaranteed to be smaller than Y's. Causally related events come out correctly ordered.

Why it matters, and an honest limitation: Lamport clocks give you a consistent, system-wide ordering of causally related events using nothing but counters and the messages you were already sending — no atomic clocks, no NTP. That is the backbone of many distributed algorithms. But there is a catch you must respect: the implication only goes one way. If X happened-before Y then X's number is smaller, but a smaller number does NOT prove X actually happened-before Y — two unrelated, concurrent events can get any ordering of numbers. To detect genuine concurrency (events that did not influence each other), you need the richer vector clock, which keeps one counter per process instead of a single number.

Process A does an event (counter 1), then sends a message carrying 2. Process B's counter was at 5; on receiving the message it takes max(5, 2) + 1 = 6. So the send (stamp 2) is correctly ordered before the receive (stamp 6). But an unrelated event on B with stamp 3 and A's send with stamp 2 are merely concurrent — the numbers cannot tell you they had no causal link.

Counters that respect cause and effect: if X could have caused Y, X's stamp is smaller. The reverse is not guaranteed.

Lamport clocks order causally related events, not real time, and a smaller timestamp does not prove a real ordering — concurrent events can compare either way. Use vector clocks when you must actually detect concurrency.

Also called
logical clock邏輯時鐘蘭波特邏輯時鐘