简体   繁体   中英

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")
        }
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM