Two coroutines in golang print numbers and letters alternately
Knowledge points
- Coroutines and chan channels
- WaitGroup
- ASCII code conversion
Coroutines and chan channels introduction
Coroutines are Go's lightweight threads that allow programs to perform multiple tasks concurrently;
A channel is a data structure of Go and a way to pass data between coroutines.
Introduction to WaitGroup
WaitGroup is a method of coroutine concurrency control
WaitGroup internally uses a counter to count how many coroutines are waiting.
The value of this counter is written before we start the coroutine (using the Add method);
Then at the end of the coroutine, decrement the counter by 1 (using the Done method);
After starting the coroutine, Wait needs to be called to wait, and it will block where Wait is called until the counter inside WaitGroup decreases to 0.
Introduction to ASCII code conversion
// rune is an alias for int32 and is equivalent to // int32 in all ways. It is // used, by convention, to distinguish character // values from integer values. // The alias of int32 is equivalent to int32 in almost all aspects// It is used to distinguish between character values and integer values type rune = int32 // We usually use the rune type to convert ASCII codes and numbers and characters// Detailed conversion correspondence Check the ASCII code table
Code Example
package main import ( "fmt" "sync" "time" ) type printDemo struct { ch chan int //Pass print numbers count int //count ok bool //Alternate control wg * //Control coroutine ends} func (p *printDemo) printNumber() { i := 1 //Print from 1 for { if { ("print number is : ", i) <- i //Passed to other Ctrip = false i++ } if i > { return } } } func (p *printDemo) printABC() { (10 * ) for { ch, ok := <- if ok && ! { //Convert to abc through ASCII code ("print abc is : %s\n", string(rune(ch+96))) = true } if ch == { ("over") () return } } } func main() { p := printDemo{} = &{} (1) = 26 = make(chan int, ) = true go () go () () }
This is the article about the implementation of the alternating printing of numbers and letters of two coroutines in golang. For more related content of the alternating printing of two coroutines in golang, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!