Skip to content

Instantly share code, notes, and snippets.

@vlad-bezden
Created August 22, 2019 21:01
Show Gist options
  • Save vlad-bezden/6eab164bf9e9fa0ae9fa32a67e074a08 to your computer and use it in GitHub Desktop.
Save vlad-bezden/6eab164bf9e9fa0ae9fa32a67e074a08 to your computer and use it in GitHub Desktop.
This example illustrates pipelines in Go. There are two channels. The first channel (channel A) is used for getting the random numbers from the first function and sending them to the second function. The second channel (channel B) is used by the second function for sending the acceptable random numbers to the third function. The third function i…
package main
import (
"fmt"
"math/rand"
"os"
"strconv"
"time"
)
var closeA = false
var data = make(map[int]bool)
func random(min, max int) int {
return rand.Intn(max-min) + min
}
func first(min, max int, out chan<- int) {
for {
if closeA {
close(out)
return
}
out <- random(min, max)
time.Sleep(1 * time.Second)
}
}
func second(out chan<- int, in <-chan int) {
for x := range in {
fmt.Print(x, " ")
_, ok := data[x]
if ok {
closeA = true
} else {
data[x] = true
out <- x
}
}
fmt.Println()
close(out)
}
func third(in <-chan int) {
var sum int
for x := range in {
sum += x
}
fmt.Printf("The sum of the random numbers is %d\n", sum)
}
func main() {
if len(os.Args) != 3 {
fmt.Println("Need two integer parameters!")
os.Exit(1)
}
n1, _ := strconv.Atoi(os.Args[1])
n2, _ := strconv.Atoi(os.Args[2])
if n1 > n2 {
fmt.Printf("%d should be smaller than %d\n", n1, n2)
return
}
rand.Seed(time.Now().UnixNano())
A := make(chan int)
B := make(chan int)
go first(n1, n2, A)
go second(B, A)
third(B)
}
/*
Input:
> go run pipeline.go 1 100
Output:
55 77 17 68 8 84 39 44 10 92 19 65 69 64 55
The sum of the random numbers is 711
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment