Golang attention to the blocking characteristics of channel

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

This blog has been migrated to www.0x520.com

Before using the channel practice encountered a problem, it seems as if the code is reasonable, and the compilation will not be a problem, but forget an important channel characteristics.

The correct code:

Package Mainimport "FMT" func foo () {    defer FMT. PRINTLN ("World")    FMT. Println ("Hello")}func sum (x, y int,c chan int) {    c <-x + Y}func main () {    foo ()    c: = make (chan int);    Go sum (24,18,c)    FMT. Println (<-c);}

If I change the code to:

Package Mainimport "FMT" func foo () {    defer FMT. PRINTLN ("World")    FMT. Println ("Hello")}//func sum (x, y int,c chan int) {//    c <-x + Y//}func main () {    foo ()/    c: = make (chan int); /    Go sum (24,18,c)//    FMT. Println (<-c);    c: = make (chan int)    D: = 2    c <-d+3     FMT. Println (<-C)}

Or

Package Mainimport "FMT" func foo () {    defer FMT. PRINTLN ("World")    FMT. Println ("Hello")}func sum (x, y int,c chan int) {    c <-x + Y}func main () {    foo ()    c: = make (chan int);    SUM (24,18,c)    FMT. Println (<-c);}

The following error will occur:

Helloworldfatal Error:all Goroutines is asleep-deadlock!goroutine 1 [Chan Send]:main.main ()    /users/john/a1.go : +0x60exit Status 2

This is why, seemingly reasonable procedures, is to ignore the channel is blocked, if not using the Go channel has been blocking the state, execution is dead loop. This feature is also convenient for many occasions.

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.