Last active
August 21, 2018 16:48
-
-
Save icholy/266636952aa25013e509b66a67f34cc4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"sync" | |
"time" | |
) | |
// Waiter allows multiple clients to wait until a certain sequence number has been reached | |
type Waiter struct { | |
cond *sync.Cond | |
seq int64 | |
} | |
// NewWaiter creates a new Waiter instance | |
func NewWaiter() *Waiter { | |
var m sync.Mutex | |
return &Waiter{ | |
cond: sync.NewCond(&m), | |
} | |
} | |
// Seq returns the current sequence number | |
func (w *Waiter) Seq() int64 { | |
w.cond.L.Lock() | |
defer w.cond.L.Unlock() | |
return w.seq | |
} | |
// Wait until the current sequence number is greater than or | |
// equal to seq | |
func (w *Waiter) Wait(seq int64) { | |
w.cond.L.Lock() | |
for w.seq < seq { | |
w.cond.Wait() | |
} | |
w.cond.L.Unlock() | |
} | |
// Update the current sequence number | |
// This method panics if seq is less than the previous one | |
func (w *Waiter) Update(seq int64) { | |
w.cond.L.Lock() | |
if seq < w.seq { | |
panic("sequence numbers cannot decrease") | |
} | |
w.seq = seq | |
w.cond.Broadcast() | |
w.cond.L.Unlock() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment