:mannotop gorutinue – manno的博客

标签: gorutinue

Manage Child Goroutines With context.Context

context.Context

As described in official Go documentation,context.Context carries deadlines, cancelation signals, and other scoped values across boundaries and between processes.

Basic usage

Context represents scope or the lifetime of the attached goroutines. When you see a function signature that looks like the following:

// Task is a function that can be and should be run as goroutine,
// it can be cancelled by cancelling the input context.
func Task(context.Context, ...args interface{})

It means that you can use the function as following:

func main() {
    // Create a new context being cancelled in 5 seconds.
    ctx, _ := context.WithTimeout(context.Background(), 5 * time.Second)
    // Start a new goroutine whose lifetime's attached to ctx.
    go task(ctx, args...)
}

The above code means that if the task function lasts over 5 seconds, it will be canceled, which helps avoid leaking goroutines.

You should design your own API in the manner shown above. When you have some long-running functions, consider attaching their lifetime to the context.

Create and derive context

To create a new and empty context, use:

// Create a new, empty, and unexecuted context.
context.Background()

Contexts can be derived, child contexts are complete once parent context is finished.

func main() {
    // Create a new context.
    parent, cancelParent := context.WithCancel(context.Background())
    // Derive child contexts from parent.
    childA, _ := context.WithTimeout(parent, 5 * time.Secound)
    childB, _ := context.WithDeadline(parent, time.Now().Add(1 * time.Minute)
    go func() {
        <-childA.Done()
        <-childB.Done()
        fmt.Println("All children are done")
    }()
    // Cancel parent make all children are cancelled.
    cancelParent()
}
// -> Result: All children are done
  • context.WithCancel(parentContext) creates a new context which completes when the returned cancel function is called or when the parent’s context finishes, whichever happens first.
  • context.WithTimeout(contextContext, 5 * time.Second) creates a new context which finishes when the returned cancel function is called or when it exceeds timeout or when the parent’s context finishes, whichever happens first.
  • context.WithDeadline(parentContext, time.Now().Add(1 * time.Minute) creates a new context which finishes when the returned cancel function deadline expires or when the parent’s context completes, whichever happens first.

There are some other methods to derive context. Check out here for further details.

Manage Child Goroutines

Now’s let solve a real-world common problem with context.Context.

The following is a very common use case in concurrency programming:

“You have 2 tasks A and B. Your main goroutine forks N goroutines (workers) running task A and M goroutines (workers) running task B. How do you gracefully shut down all child tasks when your main goroutine finished (e.g. user requests to close application)?”

package main

import (
	"context"
	"fmt"
	"os"
	"os/signal"
)

func taskA(ctx context.Context, index int) {
	done := false
	go func() {
		// Keep doing something.
		for i := 0; !done; i++ {
			fmt.Printf("A%d%d\n", index, i)
		}
	}()

	// Wait util context is cancelled.
	<-ctx.Done()
	// Turn on closing flag.
	done = true
}

func taskB(ctx context.Context, index int) {
loop:
	for i := 0; ; i++ {
		select {
		// Try pushing some message to some channel.
		case someChannel <- fmt.Sprintf("B%d%d\n", index, i):
			continue loop
			// Or when context is cancelled, finish the task.
		case <-ctx.Done():
			break loop
		}
	}
}

func main() {
	// Create application context.
	ctx, cancel := context.WithCancel(context.Background())

	// Fork n of task A with application context.
	for i := 0; i < N; i++ {
		go taskA(ctx, i)
	}

	// Fork m of task B with application context.
	for i := 0; i < M; i++ {
		go taskB(ctx, i)
	}

	// Wait for SIGINT.
	sig := make(chan os.Signal, 1)
	signal.Notify(sig, os.Interrupt)
	<-sig

	// Shutdown. Cancel application context will kill all attached tasks.
	cancel()
}