3 ms·
Would you please expand more on your first point regarding using channels instead of Locks? It’s hard for me to wrap a head around it without practical example.
by klohto 6y ago
Would you please expand more on your first point regarding using channels instead of Locks? It’s hard for me to wrap a head around it without practical example.
- deleted 6y ago[deleted]
- Philip-J-Fry 6y agoNot the OP but basically imagine that instead of locking a mutex to handle synchronised writes, you spawn a goroutine which just reads from a channel and writes the data. If that goroutine hasn't finished processing then the channel will be blocked, just like a mutex. So in your handler you can use a select statement to either write to the channel OR read from the request.Context().Done(). The request context only lives as long as the request. So if the connection drops or times out then the context gets cancelled and a value is pushed onto the done channel and your read is unblocked. Because you use a select statement then which ever operation unblocks first is what happens. If the write channel unblocks then you get to write your value. If your request context gets cancelled then you can report an error. The request context will always get cancelled eventually, unlike a mutex which will wait forever.