golang context.WithTimeout 超时处理

golang context.WithTimeout 超时处理,第1张

概述<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) { r
<span >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,_ := 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 >[work@localhost test]$ go run main.go 2016/08/18 23:22:26 map[a:1 b:fast] false2016/08/18 23:22:27 map[a:2 b:slow] true2016/08/18 23:22:28 map[a:1 b:slow] true2016/08/18 23:22:29 map[a:1 b:fast] false2016/08/18 23:22:30 map[b:fast a:2] false2016/08/18 23:22:31 map[b:slow a:2] true2016/08/18 23:22:32 map[a:1 b:fast] false2016/08/18 23:22:33 map[a:2 b:slow] true2016/08/18 23:22:34 map[a:1 b:slow] true2016/08/18 23:22:35 map[a:1 b:slow] true2016/08/18 23:22:36 map[a:1 b:slow] true^Csignal: interrupt</span>
总结

以上是内存溢出为你收集整理的golang context.WithTimeout 超时处理全部内容,希望文章能够帮你解决golang context.WithTimeout 超时处理所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1282812.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-09
下一篇 2022-06-09

发表评论

登录后才能评论

评论列表(0条)

保存