Created
September 3, 2018 11:10
-
-
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
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 ( | |
"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