The deadlock of channel in Go language

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

Recently read the Go language and wrote some sample code, when using the channel with a strange error and then exit:

"Fatal Error:all Goroutines is asleep-deadlock!"

Search on StackOverflow: http://stackoverflow.com/questions/8246065/all-goroutines-are-asleep-deadlock-error

Checked, the code for the error is as follows:

Func Chanfunc (c Chan int, D chan int) {    I: = 0    for {        Select {case            V, OK: = <-C:                If OK {                    FMT.P RINTF ("Channel C get%d\n", v)                    C <-v                    i++                    If I >= 2 {                        break                    }                } else {                    fmt. Println ("Channel C Get Fail")                } case            V, OK: = <-D:                if OK {                    FMT. PRINTF ("Channel D get%d\n", v)                    d <-v                    i++                    If I >= 2 {                        break                    }                } else {                    fmt. Println ("Channel D Get Fail")}}}    

c: = make (chan int) d: = Do (chan int)//c <-1go Chanfunc (c, D)//write to CHANNELC <-1d <-2CV: = <-CDV: = & lt;-dfmt. Printf ("CV =%d\n", CV) fmt. Printf ("DV =%d\n", DV)

In the Chanfunc function, if pipe C receives the data, it returns it immediately, but at this point in the main thread (which is called for the time being) sends data to pipe D, the result is:
1 Main Line thread is waiting and other piping D
2 Chanfunc in line C
3 C is received on the main thread
Then the entire program is deadlocked, causing the exit.


Deadlock in the program is a common mistake, but the way to take a direct exit is the first encounter, presumably in the UNIX programming Arts: "When an exception occurs, exit immediately and give enough error message."

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.