나는 Golang 루틴의 간단한 코드를 이해하려고 노력 해요 :골란에서 'time.After'와 'default'를 어떻게 사용할 수 있습니까?
package main
import (
"fmt"
"time"
)
func sleep(seconds int, endSignal chan<- bool) {
time.Sleep(time.Duration(seconds) * time.Second)
endSignal <- true
}
func main() {
endSignal := make(chan bool, 1)
go sleep(3, endSignal)
var end bool
for !end {
select {
case end = <-endSignal:
fmt.Println("The end!")
case <-time.After(5 * time.Second):
fmt.Println("There's no more time to this. Exiting!")
end = true
}
}
}
괜찮지 만 내가 왜이 "선택"블록에 간단한 기본을 사용할 수 없습니다? 이런 식으로 뭔가 :
❯ go run goroutines-timeout.go
No end signal received!
No end signal received!
No end signal received!
No end signal received!
...
The end!
을 그리고 그 이유를 이해할 수 없다 :
for !end {
select {
case end = <-endSignal:
fmt.Println("The end.")
case <-time.After(4 * time.Second):
fmt.Println("There's no more time to this. Exiting!")
end = true
default:
fmt.Println("No end signal received.")
}
}
는이 출력을 얻을 수 있습니다.
각 그렇지. 무슨 일이 일어날 지 설명해 주시겠습니까? – JimB
'time.After'의 시간이 끝나지 않는 동안'default'가 이것을 할 것으로 예상합니다. –
나는 그것을 이해하지 못한다. 디폴트의 케이스가 취해지기 (위해) 때문에,'time.After' 케이스는 실행되지 않습니다. – JimB