-
-
Save jschwinger233/97f36020fa24692aba66a7abbdd1abbc to your computer and use it in GitHub Desktop.
io tee problem
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 ( | |
| "flag" | |
| "fmt" | |
| "io" | |
| "time" | |
| ) | |
| func newReader() io.Reader { | |
| pr, pw := io.Pipe() | |
| go func() { | |
| for { | |
| s := fmt.Sprint(time.Now().UnixNano()) | |
| pw.Write([]byte(s)) | |
| time.Sleep(time.Second) | |
| } | |
| }() | |
| return pr | |
| } | |
| func read(source string, r io.Reader, notRead bool) { | |
| if notRead { | |
| time.Sleep(time.Hour) | |
| } | |
| buff := make([]byte, 1e3) | |
| for { | |
| n, err := r.Read(buff) | |
| if err != nil { | |
| break | |
| } | |
| fmt.Printf("read from [%s]: %s\n", source, buff[:n]) | |
| } | |
| } | |
| func main() { | |
| mode := flag.Int("mode", 1, "1=read all; 2=not read teeReader; 3=not read pipeReader") | |
| flag.Parse() | |
| oriReader := newReader() | |
| pipeReader, pw := io.Pipe() | |
| teeReader := io.TeeReader(oriReader, pw) | |
| switch *mode { | |
| case 1: | |
| fmt.Println("read all (mode 1)") | |
| go read("teeReader", teeReader, false) | |
| go read("pipeReader", pipeReader, false) | |
| case 2: | |
| fmt.Println("not read teeReader (mode 2)") | |
| // change the order will solve it but no outputs neither | |
| read("pipeReader", pipeReader, false) | |
| go read("teeReader", teeReader, true) | |
| case 3: | |
| fmt.Println("not read pipeReader (mode 3)") | |
| // change the order will solve it but no outputs neither | |
| read("teeReader", teeReader, false) | |
| go read("pipeReader", pipeReader, true) | |
| } | |
| c := make(chan bool) | |
| <-c | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment