Skip to content

Instantly share code, notes, and snippets.

@iamralch
Created April 16, 2015 19:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iamralch/f9fd15c2f21be2f8f10e to your computer and use it in GitHub Desktop.
Save iamralch/f9fd15c2f21be2f8f10e to your computer and use it in GitHub Desktop.
Pipeline communication between GO routines
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