Source File
context_watcher.go
Belonging Package
github.com/jackc/pgx/v5/pgconn/internal/ctxwatch
package ctxwatchimport ()// ContextWatcher watches a context and performs an action when the context is canceled. It can watch one context at a// time.type ContextWatcher struct {onCancel func()onUnwatchAfterCancel func()unwatchChan chan struct{}lock sync.MutexwatchInProgress boolonCancelWasCalled bool}// NewContextWatcher returns a ContextWatcher. onCancel will be called when a watched context is canceled.// OnUnwatchAfterCancel will be called when Unwatch is called and the watched context had already been canceled and// onCancel called.func ( func(), func()) *ContextWatcher {:= &ContextWatcher{onCancel: ,onUnwatchAfterCancel: ,unwatchChan: make(chan struct{}),}return}// Watch starts watching ctx. If ctx is canceled then the onCancel function passed to NewContextWatcher will be called.func ( *ContextWatcher) ( context.Context) {.lock.Lock()defer .lock.Unlock()if .watchInProgress {panic("Watch already in progress")}.onCancelWasCalled = falseif .Done() != nil {.watchInProgress = truego func() {select {case <-.Done():.onCancel().onCancelWasCalled = true<-.unwatchChancase <-.unwatchChan:}}()} else {.watchInProgress = false}}// Unwatch stops watching the previously watched context. If the onCancel function passed to NewContextWatcher was// called then onUnwatchAfterCancel will also be called.func ( *ContextWatcher) () {.lock.Lock()defer .lock.Unlock()if .watchInProgress {.unwatchChan <- struct{}{}if .onCancelWasCalled {.onUnwatchAfterCancel()}.watchInProgress = false}}
![]() |
The pages are generated with Golds v0.6.7. (GOOS=linux GOARCH=amd64) Golds is a Go 101 project developed by Tapir Liu. PR and bug reports are welcome and can be submitted to the issue list. Please follow @Go100and1 (reachable from the left QR code) to get the latest news of Golds. |