golang context.WithTimeout 超时处理

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)
    }
}



[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

不要企图终止goroutine,在select 中用方法包装管道来实现。

你可能感兴趣的:(golang)