Created
December 9, 2014 21:51
-
-
Save tedsuo/8aca75a18d8d7607f598 to your computer and use it in GitHub Desktop.
CancellableCopy wants to stop an in-progress io.Copy, but suffers from a race
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
| package main | |
| import ( | |
| "bytes" | |
| "errors" | |
| "io" | |
| "io/ioutil" | |
| "os" | |
| ) | |
| func CancellableCopy(r io.ReadCloser, cancelChan chan struct{}) error { | |
| defer r.Close() | |
| completeChan := make(chan error) | |
| go func() { | |
| completeChan <- thirdPartyConsumer(r) | |
| }() | |
| select { | |
| case err := <-completeChan: | |
| return err | |
| case <-cancelChan: | |
| return errors.New("canceled") | |
| } | |
| } | |
| func main() { | |
| filename := createTmpFile() | |
| file, err := os.Open(filename) | |
| panicOnError(err) | |
| defer os.Remove(file.Name()) | |
| cancel := make(chan struct{}) | |
| close(cancel) | |
| err = CancellableCopy(file, cancel) | |
| } | |
| func createTmpFile() string { | |
| tmpFile, err := ioutil.TempFile("", "some-tmp-file") | |
| panicOnError(err) | |
| _, err = tmpFile.WriteString("this is a line of text\n") | |
| panicOnError(err) | |
| err = tmpFile.Close() | |
| panicOnError(err) | |
| return tmpFile.Name() | |
| } | |
| func thirdPartyConsumer(r io.Reader) error { | |
| writer := new(bytes.Buffer) | |
| _, err := io.Copy(writer, r) | |
| return err | |
| } | |
| func panicOnError(err error) { | |
| if err != nil { | |
| panic(err.Error()) | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
here's the race: