https://github.com/virtuald/go-oncectx
A context-aware version of sync.Once
https://github.com/virtuald/go-oncectx
golang sync
Last synced: 8 months ago
JSON representation
A context-aware version of sync.Once
- Host: GitHub
- URL: https://github.com/virtuald/go-oncectx
- Owner: virtuald
- Created: 2018-08-07T17:31:01.000Z (almost 8 years ago)
- Default Branch: master
- Last Pushed: 2018-08-07T17:32:49.000Z (almost 8 years ago)
- Last Synced: 2025-02-10T12:43:16.167Z (over 1 year ago)
- Topics: golang, sync
- Language: Go
- Size: 1.95 KB
- Stars: 1
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
go-oncectx
==========
This is a version of golang's `sync.Once` that allows calling `Do` with a
context.
It is not expected that golang's stdlib will implement something like this,
see https://github.com/golang/go/issues/25312
Usage is like the `sync.Once` package, except that you must pass `Do` a context.
The function called by the Do function is run in a separate goroutine and
will always run to completion, regardless of whether the context's Done
channel is closed. However, the Do function itself will return either when
f returns or when the context Done channel is closed.
Why is this needed?
-------------------
A naive approach would do something like so:
```
func (o *Object) initSomething(ctx context.Context) {
o.once.Do(func() {
CallSomethingWithContext(ctx)
})
}
```
However, a careful reading will see that if you have multiple goroutines which
call `initSomething`, a cancellation of one of the caller's contexts will cause
initialization to fail for all callers, which is probably not an intuitive
result.