Helpers
-
Helper for implementing spin loops.
An example of a busy-wait loop. The current thread will efficiently spin, yielding control at appropriate times, until
ready
becomestrue
.func waitUntil(_ ready: AtomicBool) { var backoff = Backoff() while !ready.load() { backoff.yield() } } let ready = AtomicBool(false) DispatchQueue.global().asyncAfter(deadline: .now() + 2.0) { ready.store(true) } assert(ready.load() == false) waitUntil(ready) assert(ready.load() == true)
An example of retrying an operation until it succeeds.
See morefunc fetchMul(_ a: AtomicInt, by b: Int) -> Int { var backoff = Backoff() while true { let value = a.load() if a.compareExchangeWeak(value, value * b) == value { return value } backoff.spin() } } let a = AtomicInt(6) assert(fetchMul(a, by: 7) == 6) assert(a.load() == 42)
Declaration
Swift
public struct Backoff