่ถ
ๆถ ๅฏนไบไธไธช้่ฆ่ฟๆฅๅค้จ่ตๆบ๏ผ
ๆ่
ๆ่ๆถ่พ้ฟ็ๆไฝ็็จๅบ่่จๆฏๅพ้่ฆ็ใ
ๅพ็ไบ้้ๅ select ๏ผๅจ Go ไธญๅฎ็ฐ่ถ
ๆถๆไฝๆฏ็ฎๆด่ไผ้
็ใ
|
|
|

package main
|
|
import (
"fmt"
"time"
)
|
|
func main() {
|
ๅจ่ฟไธชไพๅญไธญ๏ผๅๅฆๆไปฌๆง่กไธไธชๅค้จ่ฐ็จ๏ผ
ๅนถๅจ 2 ็งๅไฝฟ็จ้้ c1 ่ฟๅๅฎ็ๆง่ก็ปๆใ
|
c1 := make(chan string, 1)
go func() {
time.Sleep(2 * time.Second)
c1 <- "result 1"
}()
|
่ฟ้ๆฏไฝฟ็จ select ๅฎ็ฐไธไธช่ถ
ๆถๆไฝใ
res := <- c1 ็ญๅพ
็ปๆ๏ผ<-time.After ็ญๅพ
่ถ
ๆถ๏ผ1็ง้๏ผไปฅๅๅ้็ๅผใ
็ฑไบ select ้ป่ฎคๅค็็ฌฌไธไธชๅทฒๅๅคๅฅฝ็ๆฅๆถๆไฝ๏ผ
ๅ ๆญคๅฆๆๆไฝ่ๆถ่ถ
่ฟไบๅ
่ฎธ็ 1 ็ง็่ฏ๏ผๅฐไผๆง่ก่ถ
ๆถ caseใ
|
select {
case res := <-c1:
fmt.Println(res)
case <-time.After(1 * time.Second):
fmt.Println("timeout 1")
}
|
ๅฆๆๆไปฌๅ
่ฎธไธไธช้ฟไธ็น็่ถ
ๆถๆถ้ด๏ผ3 ็ง๏ผ
ๅฐฑๅฏไปฅๆๅ็ไป c2 ๆฅๆถๅฐๅผ๏ผๅนถไธๆๅฐๅบ็ปๆใ
|
c2 := make(chan string, 1)
go func() {
time.Sleep(2 * time.Second)
c2 <- "result 2"
}()
select {
case res := <-c2:
fmt.Println(res)
case <-time.After(3 * time.Second):
fmt.Println("timeout 2")
}
}
|