简体   繁体   English

使用多个goroutine写入同一通道

[英]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. 但是在我的代码中,我两次编写了代码,但是使用了不同的go例程,并且可以正常工作。 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. goroutine从哪个执行写入或读取操作并不重要。

The Go Memory Management page explains it. 转到内存管理”页面对此进行了说明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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