Consider the following code:
type Cache struct{
cache map[string]*http.Response
AddChannel chan *http.Response
RemoveChannel chan *http.Response
FindChannel chan string
}
func (self *Cache) Run(){
select{
case resp := <-self.AddChannel:
//..code
case resp := <- self.RemoveChannel:
//..code
case find := <- self.FindChannel:
//..code
}
}
In this code, a cache is created and the Run function is called on a separate goroutine.
If a response is to be cached, it is sent through the cache's AddChannel
;
if a response is to be removed, it is sent through the RemoveChannel
and if a response needs to be found, the appropriate key is sent through the FindChannel
.
Is this a thread-safe way of protecting the cache against race conditions or is it possible that, for example, the same response could be sent to both the AddChannel
and RemoveChannel
leading to cache corruption.
I have read Go's memory model documentation and understand that it is guaranteed that sending a variable through a channel is guaranteed to happen before receiving but i'm somewhat confused as to whether this still holds if there are multiple channels to communicate to a single instance.
Sorry if I worded the question badly and thanks for your help.