Created
July 9, 2012 00:00
-
-
Save allengeorge/3073492 to your computer and use it in GitHub Desktop.
Non-Blocking Channel Write After Consumer Check
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Writes data to a channel without blocking if and only if the consumer is still alive | |
// The consumer provides a stop channel; if this channel is closed it is interpreted that the consumer no longer wants the data | |
// If data is written then this function returns true | |
func Write(data interface{}, stopChan chan interface{}, sendChan chan interface{}) (written bool, err error) { | |
select { | |
case _, ok := <-stopChan: | |
if !ok { | |
err = errors.New("consumer terminated") | |
log.Printf("chwr: %s", err.Error()) | |
} | |
default: | |
if written = WriteChanNonBlocking(data, sendChan); !written { | |
log.Printf("chwr: fail write to consumer chan") | |
} | |
} | |
return | |
} | |
// Writes data to a channel without blocking | |
// If data is written then this function returns true; in all other cases (including if data cannot be written without blocking), false is returned | |
func WriteChanNonBlocking(data interface{}, sendChan chan interface{}) (written bool) { | |
select { | |
case sendChan <- data: | |
written = true | |
default: // empty case - simply proceed | |
} | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment