Aaron2932

导航

Golang-Context库的使用

context库简介

一些场景

多线程处理任务

v01版本,等待

package main

import (
	"fmt"
	"time"
)

func main() {
	start := time.Now()
	go func(name string) {
		time.Sleep(time.Second * 6)
		fmt.Printf("(%v) Done!\n", name)
	}("user1")

	go func(name string) {
		time.Sleep(time.Second * 5)
		fmt.Printf("(%v) Done!\n", name)
	}("user2")

	time.Sleep(time.Second * 10)
	cost := time.Since(start)
	fmt.Printf("All Done! cost(%v)\n", cost)
}

结果

➜  v01 git:(master) ✗ go run example.go
(user2) Done!
(user1) Done!
All Done! cost(10.00121927s)

v02版本waitgroup

该版本和普通的利用chnnel的版本相同

package main

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

var wg sync.WaitGroup

func main() {
	start := time.Now()
	wg.Add(1)
	go func(name string) {
		time.Sleep(time.Second * 6)
		fmt.Printf("(%v) Done!\n", name)
		wg.Done()
	}("user1")

	wg.Add(1)
	go func(name string) {
		time.Sleep(time.Second * 5)
		fmt.Printf("(%v) Done!\n", name)
		wg.Done()
	}("user2")
	wg.Wait()
	cost := time.Since(start)
	fmt.Printf("All Done! cost(%v)\n", cost)
}

结果

➜  v02 git:(master) ✗ go run example.go
(user2) Done!
(user1) Done!
All Done! cost(6.001296115s)

v03 context

但是还有一些场景无法覆盖,如groutine又起了一个groutine。

爷爷和孙子需要传递,当爷爷没了,孙子的生命周期也要终结

posted on 2022-08-13 11:47  Aaron2932  阅读(18)  评论(0编辑  收藏  举报