goroutine coroutine

1 Simple example of goroutine

Source from: https://blog.csdn.net/u011957758/article/details/81159481

Channels are divided into 4 types

  • Unbuffered channel

Note: The sending operation on the unbuffered channel will be blocked until another goroutine executes the receiving operation on the corresponding channel, at which time the value transfer is completed and both goroutines continue to execute.
Code description
package main
import (
"fmt"
//"time"
)
var ch chan bool
func HelloWorld() { fmt.Println("Hello world goroutine11") fmt.Println("11111") fmt.Println("2222") ch <- true //Put a bool type value into the pipeline } func main() { ch = make(chan bool) go HelloWorld() // Start a new concurrent operation <- ch //There is in the ch pipeline It will read it out, and then execute the next sentence. If there is no content, it will always be blocked here, and fmt.Println will not be executed later ("I will output it later") }










Note: This avoids the use of sleep to wait, because after the main coroutine is executed, other coroutines will understand and exit, and may not see the printed result. The management has solved this problem properly. This is no buffering. aisle

The print result is
Insert picture description here

  • pipeline

Insert picture description here
Look at another example
package main
import (
"fmt"
"time"
)
var echo chan string
var receive chan string
// define goroutine 1
func Echo() { time.Sleep(1*time.Second) echo <- "coffee-colored sheep "Camel" } // define goroutine 2 func Receive() { temp := <- echo // block the return of the channel waiting for echo receive <- temp } func main() { echo = make(chan string) receive = make(chan string) go Echo() go Receive() getStr := <-receive // ​​Receive the return of goroutine 2 fmt.Println(getStr) }















Return result
Insert picture description here

Note: This is a pipeline

  • One-way channel type

package main
import (
"fmt"
"time"
)
// define goroutine 1
func Echo(out chan<- string) {// define output channel type
time.Sleep(1*time.Second)
out <- "coffee-colored alpaca ”
Close(out)
}
// define goroutine 2
func Receive(out chan<- string, in <-chan string) {// define output channel type and input type
temp := <-in // block the channel waiting for echo Return
out <- temp
close(out)
}
func main() { echo := make(chan string) receive := make(chan string)

go Echo(echo)
go Receive(receive, echo)

getStr := <-receive   // 接收goroutine 2的返回

fmt.Println(getStr)

}

  • Buffer pipe

Guess you like

Origin blog.csdn.net/weixin_37509194/article/details/109290677