Skip to content

Instantly share code, notes, and snippets.

@jsmits
Created December 7, 2014 12:25
Show Gist options
  • Save jsmits/272c51ab80b2a82e41a0 to your computer and use it in GitHub Desktop.
Save jsmits/272c51ab80b2a82e41a0 to your computer and use it in GitHub Desktop.
Reverse strings using a task processor
// Code from my dotGo.eu 2014 presentation
//
// Copyright (c) 2014 John Graham-Cumming
//
// Implement a factory and a task. Call run() on your factory.
package main
import (
"bufio"
"fmt"
"log"
"os"
"sync"
)
type task interface {
process()
print()
}
type factory interface {
make(line string) task
}
func run(f factory) {
var wg sync.WaitGroup
in := make(chan task)
wg.Add(1)
go func() {
defer wg.Done()
s := bufio.NewScanner(os.Stdin)
for s.Scan() {
in <- f.make(s.Text())
}
if s.Err() != nil {
log.Fatalf("Error reading STDIN: %s", s.Err())
}
close(in)
}()
out := make(chan task)
for i := 0; i < 1000; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for t := range in {
t.process()
out <- t
}
}()
}
go func() {
wg.Wait()
close(out)
}()
for t := range out {
t.print()
}
}
func Reverse(s string) string {
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}
type MyTask struct {
In string
Out string
}
func (t *MyTask) process() {
t.Out = Reverse(t.In)
}
func (t *MyTask) print() {
fmt.Println("in: ", t.In, "| out: ", t.Out)
}
type MyFactory struct{}
func (mf MyFactory) make(line string) task {
return &MyTask{In: line}
}
func main() {
run(&MyFactory{})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment