如何:
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從未收到。應該有一些方法來睡主線程,直到Receive goroutine完成。另外,接收者和發送者都知道他們將發送10個號碼,這是不雅觀的。當其他人完成工作時,其中一間公用事業機構應該關閉。我不知道該怎麼做。
EDIT1:
這裏是雙通道的實現,旅途程序發送整數來回海誓山盟之間。一個被指定爲響應者,它在接收到一個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
在發佈前修正您的縮進。 –