About the use and personal insights of goroutine and channel

Source: Internet
Author: User
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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.