這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
package mainimport "fmt"import "time"func main() { // ch := make(chan int, 10) ch := make(chan int) go produce("生產者1",ch) go produce("生產者2",ch) time.Sleep(1 * time.Second) go use(ch) time.Sleep(101 * time.Second)}func produce(pname string,ch chan int) { for i:= 0;i < 20;i++ { fmt.Println("produce", pname ," : ", i) ch <- i // 這裡需要在列印語句之後,否者可能產生理解歧義 time.Sleep(1 * time.Second) }}func use(ch chan int) { var i int loop1: i = <-ch fmt.Println("use : ",i ) goto loop1}
以上代碼有很多細節上的不完善的地方,修改:
package mainimport "fmt"import "time"func main() { // ch := make(chan int, 10) ch := make(chan int) defer close(ch) go produce("生產者1",ch) go produce("生產者2",ch) time.Sleep(1 * time.Second) go use(ch) time.Sleep(30 * time.Second)}func produce(pname string,ch chan int) { for i:= 0;i < 20;i++ { fmt.Println("produce", pname ," : ", i) ch <- i time.Sleep(1 * time.Second) }}func use(ch chan int) { for i := range ch { fmt.Println("use : ",i ) }}
多個生產者,多個消費者
package mainimport "fmt"import "time"func main() { // ch := make(chan int, 10) ch := make(chan int) defer close(ch) go produce("生產者1", ch) go produce("生產者2", ch) time.Sleep(1 * time.Second) go use("消費者1", ch) go use("消費者2", ch) time.Sleep(30 * time.Second)}func produce(pname string, ch chan int) { for i := 0; i < 20; i++ { fmt.Println("produce", pname, " : ", i) ch <- i time.Sleep(1 * time.Second) }}func use(uname string, ch chan int) { for i := range ch { fmt.Println("use", uname, " : ", i) }}