Created
December 8, 2022 16:33
-
-
Save Mec-iS/2186202c40b191ba20b9f3a867663076 to your computer and use it in GitHub Desktop.
This file contains hidden or 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" | |
"math/rand" | |
"os" | |
"strconv" | |
"time" | |
) | |
// var CLOSEA = false | |
var DATA = make(map[int]bool) | |
// use singal to avoid race condition on | |
var finished chan bool | |
func random(min, max int) int { | |
return rand.Intn(max-min) + min | |
} | |
func first(min, max int, out chan<- int) { | |
for { | |
var state bool | |
select { | |
case state =<- finished: | |
fmt.Println("close(out) state: ", state) | |
close(out) | |
close(finished) | |
return | |
// case <- time.After(time.Second * 2): | |
// fmt.Println("first() timed-out") | |
// return | |
case out <-random(min, max): | |
fmt.Println("state get number: ", state) | |
} | |
} | |
} | |
func second(out chan<- int, in <-chan int) { | |
for x := range in { | |
_, ok := DATA[x] | |
if ok { | |
fmt.Println("send finished signal ", x) | |
finished <- true | |
close(out) | |
return | |
} | |
DATA[x] = true | |
fmt.Println(x) | |
out <- x | |
} | |
} | |
func third(in <-chan int) { | |
var sum int | |
sum = 0 | |
for x2 := range in { | |
sum = sum + x2 | |
} | |
fmt.Println("The sum is ", sum) | |
} | |
func main() { | |
fmt.Println(os.Args) | |
if len(os.Args) != 3 { | |
fmt.Println("Need two integer parameters") | |
return | |
} | |
n1, _ := strconv.Atoi(os.Args[1]) | |
n2, _ := strconv.Atoi(os.Args[2]) | |
if n1 > n2 { | |
fmt.Println("%d should be smaller than %d\n", n1, n2) | |
} | |
finished = make(chan bool) | |
rand.Seed(time.Now().UnixNano()) | |
A := make(chan int) | |
B := make(chan int) | |
go first(n1, n2, A) | |
go second(B, A) | |
third(B) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment