golang 的并发控制可以通过 channel WaitGroup context 等三种方式实现
- channel
func main {
fmt.PrintLn("start")
doSomething()
fmt.PrintLn("end")
}
func doSomething() {
ch := make(chan struct{})
go func(){
for {
select {
case <-ch:
fmt.Println("goroutine exit")
return
default:
fmt.Println("goroutine running")
time.Sleep(1 * time.Second)
}
}
}()
time.Sleep(2 * time.Second)
ch <- struct{}{}
time.Sleep(2 * time.Second)
fmt.Println("main fun exit")
}
- WaitGroup
func main(){
var wg sync.WaitGroup
wg.Add(2)
go func(){
def func(){
wg.Done()
}()
fmt.PrintLn("gorouting A")
}()
go func(){
def func(){
wg.Done()
}()
fmt.PrintLn("gorouting B")
}()
wg.Wait()
time.Sleep(2 * time.Second)
fmt.Println("main fun exit")
}
- context
func main(){
ctx, cancel := context.WithCancel(context.Background())
go func(ctx context.Context){
for {
select {
case <-ctx.Done():
fmt.Println("goroutine exit")
return
default:
fmt.Println("goroutine running")
}
}
}(ctx)
time.Sleep(5 * time.Second)
fmt.Println("main fun exit")
cancel()
time.Sleep(5 * time.Second)
}