Concurrent API Design - 6.3 Graceful cancellation Flashcards
6.3 What package provides a way to stop goroutines gracefully?
The context package.
6.3 Tip: A function that accepts a context should …
always check if the context is cancelled.
6.3 Canceling in-flight http requests can done by …
By cloning a request with a cancelable context.
6.3 context.Background()
returns what?
a non-nil, empty Context. It is never cancelled, has no values, and has no deadline. It is typically used by the main function, initialisation, and tests, and as the top-level Context for incoming requests.
6.3 What does context.WithCancel(parent)
do?
returns a copy of the parent with a new Done channel. The returned context’s Done channel is closed when the returned cancel function is called or when the parent context’s Done channel is closed, whichever happens first.
Canceling this context releases resources associated with it, so code should call cancel as soon as the operations running in this Context complete.
6.3 What does context.WithTimeout(parent, timeout)
do?
WithTimeout returns a WithDeadline(parent, time.Now().Add(timeout)
6.3 What does ‘context.WithDeadline(parent, deadline)’ do?
WithDeadline returns a copy of the parent context with the deadline adjusted to be no later than d. If the parent’s deadline is already earlier than d, WithDeadline(parent, d) is semantically equivalent to parent. The returned context’s Done channel is closed when the deadline expires, when the returned cancel function is called, or when the parent context’s Done channel is closed, whichever happens first.
Canceling this context releases resources associated with it, so code should call cancel as soon as the operations running in this Context complete.
6.3 What does ctx.Err()
do?
Gets the context’s cancellation reason and returns a custom error. e.g. canceled because of a timeout.
6.3 What does context.NotifyContext(parent, os.Interrupt)
do?
Creates a notification context that will cancel itself after the interruption signal arrives.