go【goroutine】

发布时间 2023-04-19 10:51:51作者: wanghhhh

1. goroutine

1. 重点

1.要搞清楚goroutine什么时候退出
2. 控制goroutine退出
3. 把并发给调用者

 

2. 代码示例

package main

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

//1. 使用chan创建
//2 run函数消费chan,做数据上报
//3 run函数交给调用者执行, run调用结束之后将stop发送信号, 当Shutdown时候可以同stop来知道他什么时候退出, 然后通过close(t.ch),可以让整个RUN 的goroutine退出

// 重点
// 1.要搞清楚goroutine什么时候退出
// 2. 控制goroutine退出
// 3. 把并发给调用者
func main() {
	tr := NewTracker()
	// 1。 把并发行为给调用者
	go tr.Run()
	_ = tr.Event(context.Background(), "test")
	_ = tr.Event(context.Background(), "test")
	_ = tr.Event(context.Background(), "test")
	ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(10*time.Second))
	defer cancel()
	tr.Shutdown(ctx)
}

func NewTracker() *Tracker {
	return &Tracker{ch: make(chan string, 10)}
}

type Tracker struct {
	ch   chan string
	stop chan struct{}
}

func (t *Tracker) Event(ctx context.Context, data string) error {
	select {
	case t.ch <- data:
		return nil
	case <-ctx.Done():
		return ctx.Err()
	}
}

func (t *Tracker) Run() {
	for data := range t.ch {
		time.Sleep(1 * time.Second)
		fmt.Println(data)
	}
	t.stop <- struct{}{}
}

func (t *Tracker) Shutdown(ctx context.Context) {
	close(t.ch) //可以让run的goroutine退出
	select {
	case <-t.stop:
	case <-ctx.Done():
	}
}