Jakob Svenningsson
Jakob Svenningsson

Reputation: 4315

Write to same channel with multiple goroutines

This piece of code work as properly and my question is why. Ive learnt that you can only send one value to an unbuffered channel before its blocked. But in my code i write to it two times, but from different go routines, and it works. Would appreciate if someone could explain to me why!

func main(){
    var ch chan string =make(chan string)
     go write(ch)
     go write2(ch)
     go read(ch)
        select{}
}

func write(ch chan string){
    for{
        ch<-"write1"
    }
}

func write2(ch chan string){
    for{
        ch<-"write2"
    }
}

func read(ch chan string){
    for{    
        time.Sleep(time.Second)
        select{
            case res:= <-ch: fmt.Println(res)
            case <-time.After(time.Millisecond*200): fmt.Println("time out")
        }
    }
}

Upvotes: 5

Views: 13465

Answers (1)

Grzegorz Żur
Grzegorz Żur

Reputation: 49241

You can write to it again because you read from it. After read operation another write can happen. It does not really matter from which goroutine executes the write or read operation.

The Go Memory Management page explains it.

Upvotes: 8

Related Questions