Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it OK to leave a channel open?

Tags:

go

channel

Is it OK to leave a Go channel open forever (never close the channel) if I never check for its state? Will it lead to memory leaks? Is the following code OK?

func (requestCh chan<- Request) GetResponse(data RequestData) Response {     reply := make(chan Response)     requestCh <- Request{data: data, replyCh: reply}     return <-reply } 
like image 694
Kluyg Avatar asked Dec 21 '11 17:12

Kluyg


People also ask

When should you close a channel?

The Channel Closing Principle One general principle of using Go channels is don't close a channel from the receiver side and don't close a channel if the channel has multiple concurrent senders. In other words, we should only close a channel in a sender goroutine if the sender is the only sender of the channel.

What happens when you close a channel in Go?

Closing a channel indicates that no more values will be sent on it. This can be useful to communicate completion to the channel's receivers. In this example we'll use a jobs channel to communicate work to be done from the main() goroutine to a worker goroutine.


1 Answers

It's OK to leave a Go channel open forever and never close it. When the channel is no longer used, it will be garbage collected.

Note that it is only necessary to close a channel if the receiver is looking for a close. Closing the channel is a control signal on the channel indicating that no more data follows.

Design Question: Channel Closing

like image 131
peterSO Avatar answered Sep 19 '22 23:09

peterSO