Skip to content

Instantly share code, notes, and snippets.

@polebug
Created April 29, 2019 10:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save polebug/1fd4a0090e9c5161a39a9b478c829f72 to your computer and use it in GitHub Desktop.
Save polebug/1fd4a0090e9c5161a39a9b478c829f72 to your computer and use it in GitHub Desktop.
Go 使用 goroutine 和 channel 实现一个简单的`生产者-消费者`模型
package main
import (
"fmt"
"time"
)
var channel chan int = make(chan int, 1024)
func producer(role string, channel chan<- int) {
for i := 0; i < 10; i++ {
fmt.Println(role,": ", i)
channel <- i
}
fmt.Println("produce")
}
func consumer(role string, channel <-chan int) {
for i := range channel {
fmt.Println(role, ": ", i)
}
fmt.Println("consume")
}
func main(){
go producer("生产者1", channel)
go producer("生产者2", channel)
go consumer("消费者1", channel)
go consumer("消费者2", channel)
time.Sleep(5 * time.Second)
close(channel)
time.Sleep(5 * time.Second)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment