Summary - Context
- Go course
- Intermediate
- Lesson 34/80
- 4 min
Combine context types to write a cancellable request.
context summary
Root: Background. Derivations: WithCancel (manual cancel), WithTimeout (relative duration), WithDeadline (absolute time), WithValue (request-scoped data). After every derivation, defer cancel(). Cancellation spreads down the tree, never up.
Background
└─ WithTimeout(2s) ← request
├─ WithValue(kullanici)
└─ WithCancel ← parallel sub-taskscontext.AfterFunc and WithoutCancel
Go 1.21 added two helpers: context.AfterFunc(ctx, f) runs f in a separate goroutine when the context is cancelled (for cleanup); context.WithoutCancel(ctx) keeps the values but cuts off cancellation — useful for writing an audit record that must continue after the request ends.
Practice Parallel cancellation
Start three goroutines with a WithCancel context; each waits on <-ctx.Done() and calls wg.Done(). Call cancel(), wait with wg.Wait() and print "hepsi durdu".
Starter code
package main
import (
"context"
"fmt"
"sync"
)
func main() {
// buraya yaz
}Sample solution
package main
import (
"context"
"fmt"
"sync"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
var wg sync.WaitGroup
for i := 0; i < 3; i++ {
wg.Add(1)
go func() {
defer wg.Done()
<-ctx.Done()
}()
}
cancel()
wg.Wait()
fmt.Println("hepsi durdu")
}Expected output
hepsi durdu
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When a child context is cancelled, what happens to the parent?
- Its values are deleted
- Nothing; cancellation only spreads downward Correct answer
- It is cancelled too
- Its time is extended
Explanation: In the context tree the cancellation signal goes down to children; siblings and the parent are unaffected.
2 Work after cancellation
stop := context.____(ctx, func() { log.Println("temizlik") })
defer stop()
stop := context.AfterFunc(ctx, func() { log.Println("temizlik") })
defer stop()
Explanation: AfterFunc runs the given function when the context is cancelled.
3 Group summary
| Term | Meaning |
|---|---|
WithCancel |
Manual cancel |
WithTimeout |
Time limit |
WithValue |
Request data |
WithoutCancel |
Cuts off cancellation |