course/context/context-why.go

44 lines
529 B
Go
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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()
}