This is a creation in Article, where the information may have evolved or changed.
Package Mainimport "FMT" import "Time" Func main () { //ch: = Make (chan int, ten) ch: = make (chan int) go produce ("Producer 1", CH) Go Produce ("Producer 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//here need to be printed after the statement, no person may produce an understanding ambiguity time . Sleep (1 * time. Second) }}func use (ch chan int) { var i int loop1: i = <-ch fmt. Println ("Use:", i) Goto LOOP1}
The above code has many details on the imperfect place, modified:
Package Mainimport "FMT" import "Time" Func main () { //ch: = Make (chan int, ten) ch: = make (chan int) defer clos E (CH) go Produce ("Producer 1", ch) go Produce ("Producer 2", CH) time . Sleep (1 * time. Second) go use (CH) time . Sleep (* 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) }}
Multiple producers, multiple consumers
Package Mainimport "FMT" import "Time" Func main () { //ch: = Make (chan int, ten) ch: = make (chan int) defer clos E (CH) go Produce ("Producer 1", ch) go Produce ("Producer 2", CH) time . Sleep (1 * time. Second) Go Use ("Consumer 1", ch) go Use ("Consumer 2", ch) time . Sleep (* time. Second)}func Produce (pname string, ch Chan int) {for I: = 0; i <; 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) }}