Created
July 12, 2015 20:43
-
-
Save urakozz/729d2e176cdcb511eab7 to your computer and use it in GitHub Desktop.
Go read write channels
This file contains 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 "fmt" | |
type Msg struct { | |
text int | |
} | |
func write(c chan <- interface{}) { | |
for i := 0; i < 7; i++ { | |
fmt.Println("w ", i) | |
c <- &Msg{i} | |
} | |
fmt.Println("close") | |
close(c) | |
} | |
func read(c chan interface{}, q chan <- int) { | |
for { | |
select { | |
case r, closed := <-c: | |
defer func() { | |
q <- 1 | |
}() | |
fmt.Println(fmt.Sprintf("r[%d], %v", r, closed)) | |
} | |
} | |
} | |
func main() { | |
b := 1 | |
c := make(chan interface{}, b) | |
q := make(chan int) | |
go write(c) | |
go read(c, q) | |
<-q | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment