Predict the output
Node a writes, sends to b; b writes, then receives. What does each node record?
from dataclasses import dataclass, field
@dataclass
class Node:
name: str
clock: int = 0
seen: list[str] = field(default_factory=list)
def local(self, what: str) -> int:
self.clock += 1
self.seen.append(f"{what}@{self.clock}")
return self.clock
def send(self) -> int:
return self.local("send")
def receive(self, ts: int) -> None:
self.clock = max(self.clock, ts)
self.local("recv")
a, b = Node("a"), Node("b")
a.local("write x")
t = a.send()
b.local("write y")
b.receive(t)
print(a.seen, b.seen)Hint 1 of 1
receive: clock = max(local, received) + 1
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A ['write x@1', 'send@2'] ['write y@1', 'recv@3']
Correct. b's clock jumps to max(1, 2) and then increments, so the receive is ordered after the send.
A Lamport clock ticks on every local event. On receive it first jumps to max(own, message) and then ticks, so b's receive gets 3 and comes after a's send at 2.
Why not the others?
- B
['write x@1', 'send@2'] ['write y@1', 'recv@2']. Receive takes the max and then adds one. - C
['write x@1', 'send@2'] ['write y@2', 'recv@3']. b's first local event is its first tick. - D
['write x@1', 'send@1'] ['write y@1', 'recv@2']. Sending is an event and increments a's clock.