Created
April 29, 2019 10:27
-
-
Save polebug/1fd4a0090e9c5161a39a9b478c829f72 to your computer and use it in GitHub Desktop.
Go 使用 goroutine 和 channel 实现一个简单的`生产者-消费者`模型
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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