golang學習筆記——context庫
WithCancel(主進程控制子協程關閉)
package main
import (
"context"
"fmt"
"sync"
"time"
)
var wg sync.WaitGroup
func f(ctx context.Context) {
defer wg.Done()
LOOP:
for {
fmt.Println("hello world")
time.Sleep(time.Millisecond * 500)
select {
case <-ctx.Done():
break LOOP
default:
}
}
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
wg.Add(1)
go f(ctx)
time.Sleep(time.Second * 5)
//通知子協程退出
cancel()
wg.Wait()
}
WithTimeout(超時關閉)
package main
import (
"context"
"fmt"
"sync"
"time"
)
var wg sync.WaitGroup
func f(ctx context.Context) {
defer wg.Done()
LOOP:
for {
fmt.Println("hello world")
time.Sleep(time.Millisecond * 500)
select {
case <-ctx.Done(): //50毫秒自動調用
break LOOP
default:
}
}
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
//通知子協程退出
defer cancel()
wg.Add(1)
go f(ctx)
time.Sleep(time.Second * 5)
wg.Wait()
}
WithValue (key值不能爲基礎類型,應該用用戶自定義的類型)
package main
import (
"context"
"fmt"
"sync"
"time"
)
type cjp string
var wg sync.WaitGroup
func f(ctx context.Context) {
defer wg.Done()
LOOP:
for {
fmt.Println(ctx.Value(cjp("mt")))
fmt.Println("hello world")
time.Sleep(time.Millisecond * 500)
select {
case <-ctx.Done(): //50毫秒自動調用
break LOOP
default:
}
}
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
ctx = context.WithValue(ctx, cjp("mt"), "cuijiapeng")
wg.Add(1)
go f(ctx)
time.Sleep(time.Second * 5)
wg.Wait()
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.