закрытие каналов

This commit is contained in:
badkaktus 2019-10-08 11:02:00 +03:00
parent 3a7af42519
commit c16c142918
3 changed files with 22 additions and 22 deletions

View File

@ -27,7 +27,7 @@ Switch
Select
Тайм-ауты (Timeouts)
Неблокируемые операции в каналах (Non-Blocking Channel Operations)
Closing Channels
Закрытие каналов (Closing Channels)
Range over Channels
Timers
Tickers

View File

@ -1,26 +1,26 @@
// _Closing_ a channel indicates that no more values
// will be sent on it. This can be useful to communicate
// completion to the channel's receivers.
// _Закрытие_ канала означает, что по нему больше не
// будет отправлено никаких значений. Это может быть
// полезно для сообщения получателям о завершении.
package main
import "fmt"
// In this example we'll use a `jobs` channel to
// communicate work to be done from the `main()` goroutine
// to a worker goroutine. When we have no more jobs for
// the worker we'll `close` the `jobs` channel.
// В этом примере мы будем использовать канал `jobs` для
// передачи задания, которое должна быть выполнена из
// `main()` в горутине. Когда у нас больше не будет
// заданий для воркера, мы `закроем` канал `jobs`.
func main() {
jobs := make(chan int, 5)
done := make(chan bool)
// Here's the worker goroutine. It repeatedly receives
// from `jobs` with `j, more := <-jobs`. In this
// special 2-value form of receive, the `more` value
// will be `false` if `jobs` has been `close`d and all
// values in the channel have already been received.
// We use this to notify on `done` when we've worked
// all our jobs.
// Вот наш воркер. Он многократно получает из канала
// `jobs` значения `j, more := <-jobs`. В этой специальной
// форме получения с двумя значениями `more` значение
// будет `ложным`, если `jobs` были `закрыты`, а все
// значения в канале уже получены. Мы используем
// это, чтобы уведомить о `выполнении`, когда мы
// проработали все наши работы.
go func() {
for {
j, more := <-jobs
@ -34,8 +34,8 @@ func main() {
}
}()
// This sends 3 jobs to the worker over the `jobs`
// channel, then closes it.
// Отправляем 3 сообщения в канал `jobs`, и закрываем
// его.
for j := 1; j <= 3; j++ {
jobs <- j
fmt.Println("sent job", j)
@ -43,8 +43,8 @@ func main() {
close(jobs)
fmt.Println("sent all jobs")
// We await the worker using the
// [synchronization](channel-synchronization) approach
// we saw earlier.
// Мы ожидаем выполнения всех каналов используя
// [синхронизацию](channel-synchronization), рассмотренную
// нами ранее.
<-done
}

View File

@ -8,5 +8,5 @@ received job 3
sent all jobs
received all jobs
# The idea of closed channels leads naturally to our next
# example: `range` over channels.
# Идея закрытых каналов естественно приводит нас к
# следующему примеру: `range` по каналам.