可以直接套用的 channel 代码(理论篇)

生产/消费者模型

package main

import (
	"fmt"
	"sync"
)

func Producer(msg chan int, wg *sync.WaitGroup) {
	go func() {
		for i := 0; i < 10; i++ {
			msg <- i
		}
		close(msg)
		wg.Done()
	}()
}

func Consumer(msg chan int, wg *sync.WaitGroup) {
	go func() {
		for i := range msg {
			fmt.Println(i)
		}
		wg.Done()
	}()
}

func main() {
	msg := make(chan int)
	wg := sync.WaitGroup{}

	wg.Add(1)
	Producer(msg, &wg)

	wg.Add(1)
	Consumer(msg, &wg)
	wg.Add(1)
	Consumer(msg, &wg)

	wg.Wait()
}

goroutine 记录错误(errgroup只记录第一个错误,内部使用once)

package main

import (
	"context"
	"crypto/md5"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"

	"golang.org/x/sync/errgroup"
)

// Pipeline demonstrates the use of a Group to implement a multi-stage
// pipeline: a

你可能感兴趣的:(go/python,开发技巧,golang,后端)