This is a creation in Article, where the information may have evolved or changed.
Here are some of my personal insights after reading some blog posts ...
One advantage of Golang is that goroutine, like a lightweight thread. The goroutinue mechanism is like a thread pool, and when a goroutinue thread is blocked, the resource is used to invoke another goroutinue thread that is already ready. Goroutinue and the channel can be gracefully synchronized to a degree, following the simple use of goroutinue and channel.
Example one: The main thread sends information to the goroutinue threads
Package Mainimport ("FMT") func work (Stringchan Chan string) {fmt. Println (<-stringchan) fmt. PRINTLN ("Test")}func Main () {Stringchan: = Make (chan string) go work (Stringchan) stringchan<-"OK"}
The output is as follows
Oktestfinish
Through the keyword go to invoke the function work, passing in a channel parameter Stringchan, in the work function to listen to the state of Stringchan, when the main thread to Stringchan to pass a string, work will receive information, Then FMT. PRINTLN (<-stringchan) outputs the string and continues execution.
Example two: Goroutine send message to main thread
Package Mainimport ("FMT") func work (Stringchan Chan string) {stringchan<-"OK" fmt. PRINTLN ("Test")}func Main () {Stringchan: = Make (chan string) go work (Stringchan) fmt. Println (<-stringchan)}
The output is as follows
Testok
In this example, in the work function, adding a string to Stringchan does not immediately activate the FMT in main thread. Println (<-stringchan), but wait for the work function to continue after the main thread, if the work in the stringchan<-"OK" after adding a for Dead loop, run is no output.
Multithreading and thread synchronization can be done well through goroutine and channel.