select
This commit is contained in:
parent
a791406292
commit
7cd2fb92eb
@ -1,6 +1,6 @@
|
|||||||
// Go's _select_ lets you wait on multiple channel
|
// Go's _select позволяет вам ждать нескольких
|
||||||
// operations. Combining goroutines and channels with
|
// операций на канале. Сочетание горутин и каналов
|
||||||
// select is a powerful feature of Go.
|
// с помощью select'а - мощная функция Go.
|
||||||
|
|
||||||
package main
|
package main
|
||||||
|
|
||||||
@ -11,13 +11,14 @@ import (
|
|||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
|
||||||
// For our example we'll select across two channels.
|
// В нашем примере мы будем выбирать между двумя
|
||||||
|
// каналами.
|
||||||
c1 := make(chan string)
|
c1 := make(chan string)
|
||||||
c2 := make(chan string)
|
c2 := make(chan string)
|
||||||
|
|
||||||
// Each channel will receive a value after some amount
|
// Каждый канал получит значение через некоторое время,
|
||||||
// of time, to simulate e.g. blocking RPC operations
|
// например, для моделирования блокировки RPC-операций,
|
||||||
// executing in concurrent goroutines.
|
// выполняемых в параллельных горутинах.
|
||||||
go func() {
|
go func() {
|
||||||
time.Sleep(1 * time.Second)
|
time.Sleep(1 * time.Second)
|
||||||
c1 <- "one"
|
c1 <- "one"
|
||||||
@ -27,8 +28,9 @@ func main() {
|
|||||||
c2 <- "two"
|
c2 <- "two"
|
||||||
}()
|
}()
|
||||||
|
|
||||||
// We'll use `select` to await both of these values
|
// Мы будем использовать `select`, чтобы ожидать
|
||||||
// simultaneously, printing each one as it arrives.
|
// оба значения одновременно, печатая каждое из
|
||||||
|
// них по мере поступления.
|
||||||
for i := 0; i < 2; i++ {
|
for i := 0; i < 2; i++ {
|
||||||
select {
|
select {
|
||||||
case msg1 := <-c1:
|
case msg1 := <-c1:
|
||||||
|
@ -1,10 +1,10 @@
|
|||||||
# We receive the values `"one"` and then `"two"` as
|
# Мы получаем значние `"one"` и потом `"two"`, как
|
||||||
# expected.
|
# и ожидалось.
|
||||||
$ time go run select.go
|
$ time go run select.go
|
||||||
received one
|
received one
|
||||||
received two
|
received two
|
||||||
|
|
||||||
# Note that the total execution time is only ~2 seconds
|
# Обратите внимание, что общее время выполнения
|
||||||
# since both the 1 and 2 second `Sleeps` execute
|
# составляет всего ~2 секунды, так как и 1, и 2 секунды
|
||||||
# concurrently.
|
# `Sleeps` выполняются одновременно.
|
||||||
real 0m2.245s
|
real 0m2.245s
|
||||||
|
Loading…
x
Reference in New Issue
Block a user