How to realize alternating Printing of two Co-programs in go language
Most people do not understand the knowledge points of this article "go language how to achieve two collaborative process alternating printing", so the editor summarizes the following contents, detailed contents, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "go language how to achieve two collaborative process alternating printing" article.
Method 1: use two channel
Channel CA must have a buffer here, or it will end up with an error fatal error: all goroutines are asleep-deadlock!
This is because the unbuffered channel can be sent successfully only when the receiver can receive the value, otherwise it will always be in the stage of waiting for transmission. Because there is no co-program to receive data from the CA channel after the last alternate run, the deadlock will always be blocked.
Package mainimport ("fmt"sync") var wg sync.WaitGroupvar CA chan intvar CB chan intfunc main () {wg = sync.WaitGroup {} CA = make (chan int,1) CB = make (chan int) wg.Add (2) go A () go B () CA