Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

golang – deadlock with gorutine

The code below is a code that puts a value into a channel and receives and print as much as you put in. I expected it to work, but an error occurs.

package main

import (
    "fmt"
    "time"
)

func main() {
    var ch chan int
    for i := 0; i < 3; i++ {
        go func(idx int) {
            ch <- (idx + 1) * 2
        }(i)
    }

    fmt.Println("result:", <-ch)
    fmt.Println("result:", <-ch)
    fmt.Println("result:", <-ch)
    //do other work
    time.Sleep(2 * time.Second)
}

Tested on playground – https://go.dev/play/p/FFmoSMheNfu

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You are using a nil channel. The type declaration is not enough, you need to use make to initialize the channel.

ch := make(chan int)

https://go.dev/play/p/L1ewulPDYlS

There is an episode of justforfunc which explains how nil channels behave and why they are useful sometimes.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading