不要通过共享内存通信,要通过通信共享内存。
channel是golang并发编程中一种重要的数据结构,用于多个goroutine之间进行通信。
我们通常可以把channel想象成一个传送带,将goroutine想象成传送带周边的人,一个传送带的上游放上物品,通过传送带的传输,下游的人可以将物品取走。
package main
import (
"fmt"
"time"
)
func main() {
c := make(chan string, 2)
s := []string{"A", "B", "C", "D"}
go func() {
defer close(c)
for _, v := range s {
fmt.Printf("send to chan %v\n", v)
c <- v
time.Sleep(1 * time.Second)
}
}()
time.Sleep(5 * time.Second)
for v := range c {
fmt.Printf("recieved %v\n", v)
}
}
package main
import (
"fmt"
"time"
)
func main() {
c := make(chan string, 2)
s := []string{"A", "B", "C", "D"}
go func() {
//defer close(c)
for _, v := range s {
fmt.Printf("send to chan %v\n", v)
c <- v
time.Sleep(1 * time.Second)
}
}()
time.Sleep(5 * time.Second)
for v := range c {
fmt.Printf("recieved %v\n", v)
}
}