Как насчет этого:
package main
func Send (ch chan<- int) {
for i := 0; i < 10; i++ {
print(i, " sending\n")
ch <- i
}
}
func Receive (ch <-chan int) {
for i := 0; i < 10; i++ {
print(<-ch, " received\n")
}
}
func main() {
ch := make(chan int)
go Receive(ch)
Send(ch)
}
Вывод этого при запуске на golang.org:
0 sending
0 received
1 sending
2 sending
1 received
2 received
3 sending
4 sending
3 received
4 received
5 sending
6 sending
5 received
6 received
7 sending
8 sending
7 received
8 received
9 sending
Я не уверен, почему 9 не был получен. Должен быть какой-то способ усыпить основной поток, пока процедура получения не будет завершена. Кроме того, нелегко, что и получатель, и отправитель знают, что собираются отправить 10 номеров. Одна из программ должна быть отключена, когда другая закончит свою работу. Я не уверен, как это сделать.
EDIT1:
Вот реализация с двумя каналами, и подпрограммы go отправляют целые числа туда и обратно между собой. Один из них обозначен как ответчик, который отправляет только int после получения int. Ответчик просто добавляет два к полученному ему int, а затем отправляет его обратно.
package main
func Commander(commands chan int, responses chan int) {
for i := 0; i < 10; i++ {
print(i, " command\n")
commands <- i
print(<-responses, " response\n");
}
close(commands)
}
func Responder(commands chan int, responses chan int) {
for {
x, open := <-commands
if !open {
return;
}
responses <- x + 2
}
}
func main() {
commands := make(chan int)
responses := make(chan int)
go Commander(commands, responses)
Responder(commands, responses)
}
Вывод, когда я запускаю его на golang.org:
0 command
2 response
1 command
3 response
2 command
4 response
3 command
5 response
4 command
6 response
5 command
7 response
6 command
8 response
7 command
9 response
8 command
10 response
9 command
11 response