最近了解到goroutine这个概念,觉得这是真的强,想到之前用c实现生产者消费者的时候代码似乎写了不少,就像用go来实现一次。
package main import ( "fmt" "math/rand" "time" ) func productor(ch chan int) { for{ rand.Seed(time.Now().UnixNano()) i := rand.Int() ch <- i time.Sleep(1000000000) fmt.Println("product: ", i) } } func consumer(ch chan int, i int) { for{ fmt.Printf("Consume(%d): %d\n",i, <-ch) time.Sleep(3000000000) } } func main() { ch := make(chan int, 10) go consumer(ch, 1) go consumer(ch, 2) productor(ch) } Consume(1): 2104402939 product: 2104402939 Consume(2): 1319043640 product: 1319043640 Consume(1): 1801728918 product: 1801728918 Consume(2): 763982672 product: 763982672 product: 1887322392 Consume(1): 1887322392 product: 1931348537 Consume(2): 1931348537 product: 833468232 product: 939396541 Consume(1): 833468232 product: 652118081 Consume(2): 939396541 product: 1877268959由于channel、goroutine的特点,会自动实现阻塞