How to exit goroutine safely

Taken from "Go Language Advanced Programming"

1. Use chan

Insert picture description here
Insert picture description here

Insert picture description here
Insert picture description here

Insert picture description here

2. Use context

package main

import (
	"context"
	"fmt"
	"sync"
	"time"
)

func worker(ctx context.Context, wg *sync.WaitGroup) error {
    
    
	defer wg.Done()
	for {
    
    
		select {
    
    
		default:
			fmt.Println("hello")
		case <-ctx.Done():
			return ctx.Err()
		}
	}
}
func main() {
    
    
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	var wg sync.WaitGroup
	for i := 0; i < 10; i++ {
    
    
		wg.Add(1)
		go worker(ctx, &wg)
	}
	time.Sleep(time.Second)
	cancel()
	wg.Wait()
}

Guess you like

Origin blog.csdn.net/csdniter/article/details/106209695