capypad
0 Tage Serie
go / expert
Snippet

Fortgeschrittene Nebenläufigkeit mit Context-Abbruch

Context-Propagierung ist der idiomatische Weg, um Timeouts und Abbrüche über API-Grenzen und Goroutinen hinweg zu handhaben und Ressourcenlecks in komplexen asynchronen Workflows zu verhindern.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
func worker(ctx context.Context, results chan<- int) {
for {
select {
case <-ctx.Done():
return
default:
// Perform heavy computation
results <- 42
}
}
}
Erklärung
1
case <-ctx.Done():
Wird ausgelöst, wenn der übergeordnete Context abgebrochen wird oder abläuft.
2
select { ... }
Ermöglicht nicht-blockierende Prüfungen des Abbruchzustands während der Arbeit.