Skip to content

Instantly share code, notes, and snippets.

@jerryan999
Created December 20, 2021 15:41
Show Gist options
  • Save jerryan999/4d09ed40be29fce2e26e25c65b6266be to your computer and use it in GitHub Desktop.
Save jerryan999/4d09ed40be29fce2e26e25c65b6266be to your computer and use it in GitHub Desktop.
Use two goroutines to print the sequence alternately; one goroutine prints numbers, and the other prints letters.
package main
import (
"fmt"
"sync"
)
func main() {
letter, number := make(chan bool), make(chan bool)
wg := sync.WaitGroup{}
go func() {
for ch := 'A'; ch < 'Z'; ch += 2 {
letter <- true
fmt.Print(string(ch))
fmt.Print(string(ch + 1))
<-number
}
close(letter)
}()
wg.Add(1)
go func() {
start := 1
for {
number <- true
fmt.Print(start)
fmt.Print(start + 1)
start += 2
_, ok := <-letter
if ok == false {
break
}
}
wg.Done()
}()
<-number
wg.Wait()
fmt.Print("\n")
}
@jerryan999
Copy link
Author

final result is as following:

12AB34CD56EF78GH910IJ1112KL1314MN1516OP1718QR1920ST2122UV2324WX2526YZ2728

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment