【Duke】多路选择和超时控制 024 - PingPongGooo/GoFoundation GitHub Wiki

多路选择和超时控制

select

多渠道的选择

select {
case ret := <-retCh1:
    t.Logf("result %s", ret)
case ret := <-retCh2:
    t.Logf("result %s", ret)
default:
    t.Error("No one returned")
}

超时控制

select {
case ret := <-retCh:
   t.Logf("result %s", ret)
case <-time.After(time.Second * 1):
   t.Error("time out")
}

package _select

import (
"fmt"
"testing"
"time"
)

func service() string{
	time.Sleep(time.Millisecond * 500) // 耗时操作
	//time.Sleep(time.Millisecond * 50) // 耗时操作

	return "Done"
}

func AsyncService() chan string { // 返回 channel
	retCh := make(chan string,1)
	go func() { // 1. 启动协程
		ret := service()
		fmt.Println("returned result")
		retCh <- ret // 把结果放回到channel中
		fmt.Println("service exited")
	}()
	return retCh
}

func TestSelect(t *testing.T)  {

	select {
	case ret := <-AsyncService():
		t.Log(ret)
	case <-time.After(time.Millisecond * 100):
		t.Error("time out")
	}
}


=== RUN   TestSelect
--- FAIL: TestSelect (0.11s)
    select_test.go:33: time out
FAIL