Go --- channel implements producer consumer, go --- channel producer
I. No buffer zone
Package main // unbuffered channelimport ("fmt" "time") func produce (ch chan <-int) {for I: = 0; I <10; I ++ {ch <-ifmt. println ("Send:", I)} func consumer (ch <-chan int) {for I: = 0; I <10; I ++ {v: = <-chfmt. println ("Receive:", v)} // when the producer assigns a value to the channel because the channel does not have a buffer, the producer thread is blocked, until the consumer thread extracts data from the channel // After the consumer extracts the data for the first time, the consumer's thread will be blocked during the next loop, because the producer has not stored the data, the program will execute the // producer thread. In this way, the program continuously switches between the consumer and the producer until the loop ends. Func main () {ch: = make (chan int) go produce (ch) go consumer (ch) time. Sleep (1 * time. Second )}
2. Buffer Zone
In this program, the buffer can store 10 int-type integers. during the execution of the producer thread, the thread will not be blocked. The 10 integers will be stored in the channel at a time. During reading, it is also a one-time read.
Package main // channelimport ("fmt" time ") func produce (ch chan <-int) {for I: = 0; I <10; I ++ {ch <-ifmt. println ("Send:", I)} func consumer (ch <-chan int) {for I: = 0; I <10; I ++ {v: = <-chfmt. println ("Receive:", v)} func main () {ch: = make (chan int, 10) go produce (ch) time. sleep (1 * time. second )}
View comments