Go从0开发(12)_context

场景 1

package main

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

var wg sync.WaitGroup
var notify bool

func f1() {
defer wg.Done()
i := 0
for {
i++
fmt.Println(i)
time.Sleep(time.Millisecond*500)
if notify {
break
}
}
}

func f11() {
wg.Add(1)
go f1()
time.Sleep(time.Second*5)
notify = true
wg.Wait()
}


func main() {
f11()
}


场景2

package main

import (
"fmt"
"sync"
"time"
)
var wg sync.WaitGroup
var ch = make(chan bool,1)

func c1(){
defer wg.Done()

i := 0
XXXXAAAAA:
for {
i++
fmt.Println(i)
time.Sleep(time.Millisecond*500)
select {
case x:= <-ch:
fmt.Println(x)
break XXXXAAAAA
//return
default:

}
}

}

func c11() {
wg.Add(1)
go c1()
time.Sleep(time.Second * 5)
ch <- true
wg.Wait()
}

func main() {
c11()
}

场景3

package main

import (
"context"
"fmt"
"sync"
"time"
)
var wg sync.WaitGroup

func c1(ctx context.Context){
defer wg.Done()
go c2(ctx)
i := 0
XXXXX1:
for {
i++
fmt.Println("A:",i)
time.Sleep(time.Millisecond*500)
select {
case <- ctx.Done():
break XXXXX1
default:

}
}

}

func c2(ctx context.Context){
defer wg.Done()
i := 0
XXXXX2:
for {
i++
fmt.Println("B:",i)
time.Sleep(time.Millisecond*500)
select {
case <- ctx.Done():
break XXXXX2
default:

}
}

}

func c11() {
ctx,cancel := context.WithCancel(context.Background())
wg.Add(1)
go c1(ctx)
time.Sleep(time.Second * 5)
cancel()
wg.Wait()
}

func main() {
c11()
}





伍先生
  • 职业: 程序员,产品
  • 码龄: 4.1
  • 技能: PHP Go 前端
  • 微信: JwCode
  • 公众号/小程序: 渐悟分享