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

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

View File

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