golang context.WithTimeout 超时处理
发布时间:2020-12-16 18:27:57 所属栏目:大数据 来源:网络整理
导读:span style="font-size:18px;color:#3333ff;"package mainimport ( "golang.org/x/net/context" "log" "math/rand" "time")func test(is_first *bool,prev_map *map[string]string) { rand.Seed(int64(time.Now().Nanosecond())) ch := make(chan bool) ctx,
<span style="font-size:18px;color:#3333ff;">package main import ( "golang.org/x/net/context" "log" "math/rand" "time" ) func test(is_first *bool,prev_map *map[string]string) { rand.Seed(int64(time.Now().Nanosecond())) ch := make(chan bool) ctx,_ := context.WithTimeout(context.Background(),50*time.Millisecond) go func() { if *is_first { (*prev_map)["a"] = "1" } else { (*prev_map)["a"] = "2" } time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond) ch <- true }() select { case <-ch: *is_first = false (*prev_map)["b"] = "fast" return case <-ctx.Done(): *is_first = true (*prev_map)["b"] = "slow" return } } func main() { is_first := true prev_map := make(map[string]string) for { test(&is_first,&prev_map) time.Sleep(time.Second) log.Println(prev_map,is_first) } }</span>
<span style="font-size:18px;color:#3333ff;">[work@localhost test]$ go run main.go 2016/08/18 23:22:26 map[a:1 b:fast] false 2016/08/18 23:22:27 map[a:2 b:slow] true 2016/08/18 23:22:28 map[a:1 b:slow] true 2016/08/18 23:22:29 map[a:1 b:fast] false 2016/08/18 23:22:30 map[b:fast a:2] false 2016/08/18 23:22:31 map[b:slow a:2] true 2016/08/18 23:22:32 map[a:1 b:fast] false 2016/08/18 23:22:33 map[a:2 b:slow] true 2016/08/18 23:22:34 map[a:1 b:slow] true 2016/08/18 23:22:35 map[a:1 b:slow] true 2016/08/18 23:22:36 map[a:1 b:slow] true ^Csignal: interrupt</span> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |