Untitled
unknown
plain_text
8 months ago
866 B
15
Indexable
package main
import (
"fmt"
"sync"
)
func main() {
ch := make(chan int)
evenCh := make(chan struct{})
oddCh := make(chan struct{})
var wg sync.WaitGroup
wg.Add(2)
go even(ch, evenCh, oddCh, &wg)
go odd(ch, oddCh, evenCh, &wg)
// Start the sequence with even
go func() {
evenCh <- struct{}{}
}()
// Collect output
go func() {
wg.Wait()
close(ch)
}()
for v := range ch {
fmt.Println(v)
}
}
func even(ch chan int, myTurn chan struct{}, nextTurn chan struct{}, wg *sync.WaitGroup) {
defer wg.Done()
for i := 0; i <= 20; i += 2 {
<-myTurn
ch <- i
if i < 20 { // Avoid sending again after the last value
nextTurn <- struct{}{}
}
}
}
func odd(ch chan int, myTurn chan struct{}, nextTurn chan struct{}, wg *sync.WaitGroup) {
defer wg.Done()
for i := 1; i <= 19; i += 2 {
<-myTurn
ch <- i
nextTurn <- struct{}{}
}
}
Editor is loading...
Leave a Comment