таймауты
This commit is contained in:
parent
7cd2fb92eb
commit
80c656cd73
@ -25,7 +25,7 @@ Switch
|
|||||||
Синхронизация канала (Channel Synchronization)
|
Синхронизация канала (Channel Synchronization)
|
||||||
Направления канала (Channel Directions)
|
Направления канала (Channel Directions)
|
||||||
Select
|
Select
|
||||||
Timeouts
|
Тайм-ауты (Timeouts)
|
||||||
Non-Blocking Channel Operations
|
Non-Blocking Channel Operations
|
||||||
Closing Channels
|
Closing Channels
|
||||||
Range over Channels
|
Range over Channels
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
// _Timeouts_ are important for programs that connect to
|
// _Тайм-ауты_ важны для программ, которые подключаются
|
||||||
// external resources or that otherwise need to bound
|
// к внешним ресурсам или которым необходимо ограничить
|
||||||
// execution time. Implementing timeouts in Go is easy and
|
// время выполнения. Тайм-ауты в Go реализуются легко
|
||||||
// elegant thanks to channels and `select`.
|
// и элегантно благодаря каналам и `select`'ам.
|
||||||
|
|
||||||
package main
|
package main
|
||||||
|
|
||||||
@ -12,24 +12,24 @@ import (
|
|||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
|
||||||
// For our example, suppose we're executing an external
|
// В нашем примере предположим, что мы выполняем внешний
|
||||||
// call that returns its result on a channel `c1`
|
// вызов, который возвращает результат на канале `c1`
|
||||||
// after 2s. Note that the channel is buffered, so the
|
// через 2с. Обратите внимание, что канал буферизован,
|
||||||
// send in the goroutine is nonblocking. This is a
|
// поэтому отправка в goroutine неблокирующая. Это
|
||||||
// common pattern to prevent goroutine leaks in case the
|
// обычная схема предотвращения утечек горутин в случае,
|
||||||
// channel is never read.
|
// если канал никогда не читается.ё
|
||||||
c1 := make(chan string, 1)
|
c1 := make(chan string, 1)
|
||||||
go func() {
|
go func() {
|
||||||
time.Sleep(2 * time.Second)
|
time.Sleep(2 * time.Second)
|
||||||
c1 <- "result 1"
|
c1 <- "result 1"
|
||||||
}()
|
}()
|
||||||
|
|
||||||
// Here's the `select` implementing a timeout.
|
// Вот `select`, реализующий тайм-аут. `res := <-c1`
|
||||||
// `res := <-c1` awaits the result and `<-Time.After`
|
// ожидает результата, а `<-Time.After` ожидает
|
||||||
// awaits a value to be sent after the timeout of
|
// значения, которое будет отправлено после истечения
|
||||||
// 1s. Since `select` proceeds with the first
|
// времени ожидания 1с. Поскольку `select` продолжает
|
||||||
// receive that's ready, we'll take the timeout case
|
// работу с первым полученным запросом, мы возьмем
|
||||||
// if the operation takes more than the allowed 1s.
|
// тайм-аут, если операция займет больше разрешенных 1с.
|
||||||
select {
|
select {
|
||||||
case res := <-c1:
|
case res := <-c1:
|
||||||
fmt.Println(res)
|
fmt.Println(res)
|
||||||
@ -37,8 +37,9 @@ func main() {
|
|||||||
fmt.Println("timeout 1")
|
fmt.Println("timeout 1")
|
||||||
}
|
}
|
||||||
|
|
||||||
// If we allow a longer timeout of 3s, then the receive
|
// Если мы допустим время ожидания более 3с, то
|
||||||
// from `c2` will succeed and we'll print the result.
|
// получение от `c2` будет успешным, и мы распечатаем
|
||||||
|
// результат.
|
||||||
c2 := make(chan string, 1)
|
c2 := make(chan string, 1)
|
||||||
go func() {
|
go func() {
|
||||||
time.Sleep(2 * time.Second)
|
time.Sleep(2 * time.Second)
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
# Running this program shows the first operation timing
|
# Запуск этой программы показывает время ожидания
|
||||||
# out and the second succeeding.
|
# первой и второй успешной операции.
|
||||||
$ go run timeouts.go
|
$ go run timeouts.go
|
||||||
timeout 1
|
timeout 1
|
||||||
result 2
|
result 2
|
||||||
|
Loading…
x
Reference in New Issue
Block a user