The interview question itself is not my original, extracted from the big guy feel useful can give big guy a start bar
Print numbers and letters alternately
Problem description
Using two goroutines to print sequences alternately, one to print numbers and the other to print letters, the result looks like this:
12AB34CD56EF78GH910IJ1112KL1314MN1516OP1718QR1920ST2122UV2324WX2526YZ2728
Copy the code
Their thinking
The problem is simple: use channel to control the printing progress. Two channels are used to control the printing sequence of numbers and letters respectively. When the number is printed, the channel informs the letter to print, and the letter to print is notified to print, and then the work repeats.
letter,number := make(chan bool),make(chan bool)
wait := sync.WaitGroup{}
go func(a) {
i := 1
for {
select {
case <-number:
fmt.Print(i)
i++
fmt.Print(i)
i++
letter <- true
}
}
}()
wait.Add(1)
go func(wait *sync.WaitGroup) {
i := 'A'
for{
select {
case <-letter:
if i >= 'Z' {
wait.Done()
return
}
fmt.Print(string(i))
i++
fmt.Print(string(i))
i++
number <- true
}
}
}(&wait)
number<-true
wait.Wait()
Copy the code
Project Execution process
- Define two bool channels assigned to letter and number
- Define a wait group that blocks the coroutine until the entire coroutine is finished
- The first coroutine (hereafter called A coroutine) is started in an infinite loop, but due to select multiplexing, the number value is blocked and A coroutine switch occurs
- Wait group atom +1
- The second coroutine (hereafter called coroutine B) is started and passed into the coroutine namespace, iterating through the select letter but blocking because of letter false
- The number channel pushes true, and the number value in coroutine A gets true, and the code executes
- According to the loop I in coroutine A with the initial value of 1, print 1, I increment by 1, print I again, print 2, increment by 1, and put bool true
- ‘A’ >= ‘Z’ false ‘done’ return ‘A’, ‘B’, ‘number ‘,’ true ‘, ‘A’
- Wait until I >= ‘Z’ triggers wait group -1 and exits the loop. Atomic lock 0 detected in WaitGroup, program can exit after execution
- The entire program life cycle ends