Created
April 16, 2015 19:36
-
-
Save iamralch/f9fd15c2f21be2f8f10e to your computer and use it in GitHub Desktop.
Pipeline communication between GO routines
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 ( | |
"encoding/json" | |
"fmt" | |
"io" | |
"sync" | |
"time" | |
) | |
type Message struct { | |
Type int `json:"type"` | |
Content string `json:"content"` | |
} | |
func main() { | |
reader, writer := io.Pipe() | |
go func() { | |
id := 1 | |
for { | |
fmt.Printf("Sending %d\n", id) | |
msg, _ := json.Marshal(&Message{Type: id, Content: "Content"}) | |
writer.Write(msg) | |
id = id + 1 | |
} | |
}() | |
fmt.Println("[PAUSED] It will start receiving in 10s") | |
time.Sleep(time.Second * 10) | |
var done sync.WaitGroup | |
done.Add(1) | |
go func() { | |
for { | |
var message Message | |
json.NewDecoder(reader).Decode(&message) | |
fmt.Printf("Received: %v\n", message) | |
} | |
fmt.Println("Receiving [STOPPED]") | |
done.Wait() | |
}() | |
done.Wait() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment