неблокирующие каналы
This commit is contained in:
parent
80c656cd73
commit
3a7af42519
@ -26,7 +26,7 @@ Switch
|
||||
Направления канала (Channel Directions)
|
||||
Select
|
||||
Тайм-ауты (Timeouts)
|
||||
Non-Blocking Channel Operations
|
||||
Неблокируемые операции в каналах (Non-Blocking Channel Operations)
|
||||
Closing Channels
|
||||
Range over Channels
|
||||
Timers
|
||||
|
@ -1,7 +1,8 @@
|
||||
// Basic sends and receives on channels are blocking.
|
||||
// However, we can use `select` with a `default` clause to
|
||||
// implement _non-blocking_ sends, receives, and even
|
||||
// non-blocking multi-way `select`s.
|
||||
// Стандартные отправители и получатели в каналах
|
||||
// являются блокирующими.Тем не менее, мы можем
|
||||
// использовать `select` с выбором `по умолчанию` для
|
||||
// реализации _неблокирующих_ отправителей, получателей
|
||||
// и даже неблокирующего множественного `select`'а.
|
||||
|
||||
package main
|
||||
|
||||
@ -11,10 +12,10 @@ func main() {
|
||||
messages := make(chan string)
|
||||
signals := make(chan bool)
|
||||
|
||||
// Here's a non-blocking receive. If a value is
|
||||
// available on `messages` then `select` will take
|
||||
// the `<-messages` `case` with that value. If not
|
||||
// it will immediately take the `default` case.
|
||||
// Вот неблокирующее получение. Если значение
|
||||
// доступно в `messages`, тогда `select` выберет
|
||||
// `<-messages` с этим значением. Если нет, он
|
||||
// сразу же примет случай `по-умолчанию`.
|
||||
select {
|
||||
case msg := <-messages:
|
||||
fmt.Println("received message", msg)
|
||||
@ -22,10 +23,11 @@ func main() {
|
||||
fmt.Println("no message received")
|
||||
}
|
||||
|
||||
// A non-blocking send works similarly. Here `msg`
|
||||
// cannot be sent to the `messages` channel, because
|
||||
// the channel has no buffer and there is no receiver.
|
||||
// Therefore the `default` case is selected.
|
||||
// Неблокирующая отправка работает аналогично.
|
||||
// Здесь `msg` не может быть отправлено в канал
|
||||
// `messages`, потому что у канала нет буфера и
|
||||
// нет получателя. Поэтому выбирается действие
|
||||
// `по-умолчанию`.
|
||||
msg := "hi"
|
||||
select {
|
||||
case messages <- msg:
|
||||
@ -34,10 +36,11 @@ func main() {
|
||||
fmt.Println("no message sent")
|
||||
}
|
||||
|
||||
// We can use multiple `case`s above the `default`
|
||||
// clause to implement a multi-way non-blocking
|
||||
// select. Here we attempt non-blocking receives
|
||||
// on both `messages` and `signals`.
|
||||
// Мы можем использовать несколько `case`'ов перед
|
||||
// `действием по-умолчанию` для реализации
|
||||
// многоцелевого неблокирующего выбора. Здесь мы
|
||||
// пытаемся получить неблокирующее получение
|
||||
// `messages` и `signals`.
|
||||
select {
|
||||
case msg := <-messages:
|
||||
fmt.Println("received message", msg)
|
||||
|
Loading…
x
Reference in New Issue
Block a user