Once
type OnceOnce runs a function exactly once, however many goroutines ask. Onces compare by identity.
A Once guards work that must happen exactly once: setting up shared state, opening a connection, closing a channel. The Once namespace holds a function that makes a once, one that runs work through it, and one that wraps a loader so its value is computed on first use and cached.
Details
- The first call runs its function. A call made while that run is going waits for it, so after any call returns, everything the run wrote is visible, from any goroutine.
- A panic in the function completes the once too. The function is not run again, and every call, waiting or later, panics with the same panic.
- A
Onceis a reference value: a copy in a record field, a parameter, or a closure is the same once.
Basic examples
Once.new makes a once, and Once.do runs a function through it. Only the first call runs:
let setup = Once.new()
Once.do(setup, { println("connecting") })
Once.do(setup, { println("connecting") })
println("ready")connecting
readyOnce.value wraps a loader. The returned function runs it on its first call and returns the cached value after that:
let config = Once.value({
println("loading config")
"debug=true"
})
println(config())
println(config())loading config
debug=true
debug=trueScope
A once in a record field guards each record on its own. A field default gives every record a fresh one:
type Cache = { name: string, warmed: Once = Once.new() }
func Cache.warm(c: Cache) {
c.warmed.do({ println("warming ${c.name}") })
}
let users = Cache{ name: "users" }
let posts = Cache{ name: "posts" }
users.warm()
posts.warm()
users.warm()warming users
warming postsA once passed around is still one once. Running it through a copy completes it for every copy:
let shared = Once.new()
let alias = shared
alias.do({ println("first run") })
shared.do({ println("second run") })
println(shared == alias)
println(shared == Once.new())
println(shared)first run
true
false
OnceFunctions by job
Running work once
- Once.new: a new once that has not run yet
- Once.do: run a function on the first call only; later calls wait for it and do nothing
Computing a value once
- Once.value: a function that runs the loader on its first call and caches its value
Applications
Load shared state on first use
Several goroutines ask for the same table at once. The loader runs once, and every goroutine gets its result:
let loads = Atomic.new(0)
let table = Once.value({
loads.add(1)
Time.sleep(10ms)
Map{ "ant": 6, "bee": 4 }
})
let legs = Array.filled(3, 0)
let wg = WaitGroup.new()
for i in Array.range(0, 3) {
wg.add(1)
go {
defer { wg.done() }
legs[i] = table().get("ant") ?? 0
}
}
wg.wait()
println(legs)
println(loads.load())[6, 6, 6]
1Close a channel exactly once
A second close of a channel panics. When any of several workers may decide to stop, a once makes the close happen exactly once:
let stop: Channel[bool] = Channel.new()
let closeStop = Once.new()
Parallel.each(Array.range(0, 3), func(_: int, ctx: Context) {
closeStop.do({ stop.close() })
}, limit: 3)
println(stop.isClosed())trueProperties and relations
Once.value(f) does what a once, a nullable variable, and Once.do do by hand, without the variable or the ?? at every read:
let once = Once.new()
var cached: string | null = null
func byHand(): string {
once.do({ cached = "ready" })
cached ?? panic("unreachable")
}
let lazy = Once.value({ "ready" })
assert(byHand() == lazy())
assert(lazy() == lazy())Each once completes on its own:
let first = Once.new()
let second = Once.new()
var runs = 0
first.do({ runs += 1 })
first.do({ runs += 1 })
second.do({ runs += 1 })
assert(runs == 2)
assert(first != second)Possible issues
A once made inside a function guards nothing
A once created on every call is a new once every time, so its function runs every time. Make it at the top level or in a record, where it outlives the calls:
func connect() {
let once = Once.new()
once.do({ println("connecting") })
}
connect()
connect()connecting
connectingA failed run is not retried
After the function panics, the once is complete, and every later call panics with the same message:
let once = Once.new()
let first = Panic.catch({ once.do({ panic("config missing") }) })
first is Err // true
once.do({ println("retrying") }) // panic: config missingOnce.value caches a returned Err the same way. To retry after a failure, call the loader directly and keep its value only after it succeeds, for example under a Mutex.
Calling a once from its own function waits forever
A call made while the run is going waits for that run to finish. So the function cannot call the same once, directly or through a helper: the inner call waits for the run it is part of, and the program hangs. Give each step its own once, so the outer step can call the inner one:
let loadKeys = Once.new()
let loadConfig = Once.new()
func keys() {
loadKeys.do({ println("loading keys") })
}
func config() {
loadConfig.do({
keys()
println("loading config")
})
}
config()
keys()
config()loading keys
loading configOnce.do has no result
Once.do returns void. Use Once.value for work whose value you need:
let once = Once.new()
let name = once.do({ "ant" })
println(name.length()) // error: void has no field or function lengthSee also
- Mutex: guard shared state that changes more than once
- Atomic: one value read and written atomically
- WaitGroup: wait for goroutines to finish
- Panic.catch: recover from the panic of a failed run
- Concurrency: how goroutines, channels, and sync objects fit together
