Skip to content

Instantly share code, notes, and snippets.

@janithl
Created September 3, 2018 11:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save janithl/bb45d338bbc0e20503ddeba8b57b39f6 to your computer and use it in GitHub Desktop.
Save janithl/bb45d338bbc0e20503ddeba8b57b39f6 to your computer and use it in GitHub Desktop.
A simple Goroutine exercise, where a worker thread reads user input through a channel
package main
import (
"bufio"
"fmt"
"os"
"time"
)
type message struct {
id int
content string
}
func (m *message) getID() string {
return fmt.Sprintf("#%d", m.id)
}
func readerWorker(readQueue <-chan message) {
for {
queueMessage := <-readQueue
time.Sleep(3000 * time.Millisecond)
fmt.Printf("Worker reads message %s from the queue: %s", queueMessage.getID(), queueMessage.content)
}
}
func main() {
id := 1000
reader := bufio.NewReader(os.Stdin)
readQueue := make(chan message, 3)
go readerWorker(readQueue)
for {
fmt.Print("Enter text: ")
userInput, _ := reader.ReadString('\n')
if userInput == "exit\n" {
return
}
id++
queueMessage := message{id: id, content: userInput}
readQueue <- queueMessage
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment