← Zurück zum Kurs: Go from scratch

Context: cancellation and deadlines, and week 7 review

Video folgt in Kürze

When you launch a goroutine, sooner or later you need to be able to tell it: "stop, your work is no longer needed". Maybe the user closed the connection, maybe the operation took too long, maybe another part of the program failed. If there is no way to notify it, the goroutine keeps using memory and CPU for nothing: a goroutine leak. The context package of the standard library solves this with an object that travels through your functions and carries two things: a cancellation signal and, optionally, a maximum deadline.

Creating and cancelling a context

Every tree of contexts is born from context.Background(), an empty context that is never cancelled; it is used in main and in tests. From it you derive child contexts: context.WithCancel gives you the child and a cancel function that cancels it by hand; context.WithTimeout and context.WithDeadline cancel themselves when the time runs out. When you cancel a parent, all its children are cancelled too. You must always call cancel (usually with defer cancel()) to release internal resources, even if the deadline has already expired: go vet warns you if you forget.

go
package main

import (
	"context"
	"errors"
	"fmt"
	"time"
)

// slowOperation waits for the work or for the context, whichever comes first.
func slowOperation(ctx context.Context) error {
	select {
	case <-time.After(2 * time.Second):
		fmt.Println("operation finished")
		return nil
	case <-ctx.Done():
		return ctx.Err()
	}
}

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
	defer cancel()

	err := slowOperation(ctx)
	fmt.Println("result:", err)                              // result: context deadline exceeded
	fmt.Println(errors.Is(err, context.DeadlineExceeded)) // true
}

How a goroutine obeys

The context kills nothing by itself: Go has no way to stop a goroutine from outside. What it does is offer the channel ctx.Done(), which is closed when the context is cancelled. Your code must listen to it, usually inside a select, and exit in an orderly way. After Done is closed, ctx.Err() explains the reason: context.Canceled if someone called cancel, or context.DeadlineExceeded if the deadline passed. By convention, a function that receives a context declares it as the first parameter and calls it ctx; never store it inside a long-lived struct.

go
package main

import (
	"context"
	"fmt"
)

// counter produces 1, 2, 3... until the context is cancelled.
func counter(ctx context.Context) <-chan int {
	out := make(chan int)
	go func() {
		defer close(out)
		for i := 1; ; i++ {
			select {
			case out <- i:
			case <-ctx.Done():
				return // stop producing: no leaked goroutine
			}
		}
	}()
	return out
}

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	for n := range counter(ctx) {
		fmt.Println(n) // 1, 2, 3
		if n == 3 {
			break
		}
	}
	cancel() // tell the producer to stop
	fmt.Println("stopped")
}

Notice the pattern: the producer uses select with two cases, sending the next number or learning about the cancellation. Without the ctx.Done() case, after the break the goroutine would stay blocked forever trying to send 4, and nobody would collect it. This is the most common mistake with channels and contexts: forgetting that every goroutine needs an exit. You can also pass values in the context with context.WithValue, but use it only for request data (for example a trace identifier), never for normal function parameters.

Week 7 review

  • go f() launches a goroutine; main does not wait for it.
  • Channels communicate goroutines; make(chan T, n) creates a buffer of n.
  • close(ch) is done by the sender; for v := range ch ends when it is closed.
  • WaitGroup waits for a group; Mutex protects shared data; select waits on several channels.
  • context cancels by signal or deadline; it is passed as the first parameter.
  • go test -race detects race conditions.

Teste dein Wissen

Frage 1 von 6

What does context.WithTimeout do?

✎ Meine Notizen

Nur in diesem Browser gespeichert. Melde dich an, um es im Konto zu behalten.0/5000 Zeichen

← ZurückWeiter →