Last active
August 19, 2019 02:35
-
-
Save mhewedy/2e7a07b4586e37076cc3680a777eca48 to your computer and use it in GitHub Desktop.
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" | |
"github.com/fatih/color" | |
"sync" | |
) | |
func main() { | |
var wg sync.WaitGroup | |
wg.Add(11) | |
const numElements = 20 | |
ch := make(chan int) | |
orderCh := make(chan int, numElements) | |
for i := 0; i < 10; i++ { | |
go func(i int) { | |
for v := range ch { | |
fmt.Println(color.RedString("unordered element:%v", v)) | |
orderCh <- v | |
} | |
wg.Done() | |
}(i) | |
} | |
for i := 0; i < numElements; i++ { | |
ch <- i | |
} | |
close(ch) | |
var values = make([]int, 0, numElements) | |
for v := range orderCh { | |
latest := -1 | |
if len(values) > 0 { | |
latest = values[len(values)-1] | |
} | |
if v == latest+1 { | |
values = append(values, v) | |
fmt.Println(color.GreenString("ordered element:%v", v)) | |
} else { | |
orderCh <- v // resend to the channel | |
fmt.Println("value", color.YellowString("%v", v), "resent") | |
} | |
if len(values) == cap(values) { | |
close(orderCh) | |
} | |
} | |
wg.Done() | |
wg.Wait() | |
} |
Author
mhewedy
commented
Aug 18, 2019
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment