course/context/context-why.go

44 lines
529 B
Go
Raw Normal View History

2024-07-29 00:25:13 +08:00
package main
import (
"fmt"
"sync"
"time"
)
var wg sync.WaitGroup
//var notify bool
//var exitChan chan bool = make(chan bool, 1)
// why context
func f() {
defer wg.Done()
//loop:
for {
fmt.Println("hello world")
time.Sleep(time.Millisecond * 500)
//if notify {
// break
//} //变量
//select {
//case <-exitChan:
// break loop
//default:
//} //channel 版本
}
}
func main() {
wg.Add(1)
go f()
time.Sleep(time.Second * 3)
//如何通知goroutine退出
//exitChan <- true
wg.Wait()
}