Skip to content

Commit

Permalink
Merge pull request #45 from burned42/add_coffee_maker_challenge_code
Browse files Browse the repository at this point in the history
add coffee maker challenge code
  • Loading branch information
niklas-heer committed Feb 15, 2019
2 parents 48d7ad1 + 55e29fc commit 83ea10a
Show file tree
Hide file tree
Showing 2 changed files with 96 additions and 0 deletions.
10 changes: 10 additions & 0 deletions slides/2019/031_go-to-grpc/coffee-maker-challenge/README.md
@@ -0,0 +1,10 @@
We (@dersell and @burned42) tried to solve the challenge :)
It's not pretty but it works and we thought it would be nice to share
the code anyway.

As we remembered the constrains where that the coffee maker should be
able to make multiple coffees at the same time and you should be able
to abort each coffee if you like, so that's what we implemented. The
coffee maker produces 10 coffees and you can abort a specific coffee by
typing in the number of the coffee.

86 changes: 86 additions & 0 deletions slides/2019/031_go-to-grpc/coffee-maker-challenge/main.go
@@ -0,0 +1,86 @@
package main

import (
"fmt"
"sync"
"time"
)

var waitGroup sync.WaitGroup

const coffeeCount = 10

func main() {
var coffeeFinished [coffeeCount]chan bool
for i := 0; i < coffeeCount; i++ {
coffeeFinished[i] = make(chan bool)
}
go runAbortScreen(coffeeFinished)

for i := 0; i < coffeeCount; i++ {
waitGroup.Add(1)
go func(i int) {
go makeCoffee(i+1, coffeeFinished[i])
<-coffeeFinished[i]
waitGroup.Done()
}(i)

time.Sleep(time.Second)
}

waitGroup.Wait()
}

func runAbortScreen(isAbort [coffeeCount]chan bool) {
fmt.Println("Press a number to cancel making coffee!")

for {
var key int
fmt.Scanf("%d", &key)
fmt.Println("Cancelling coffee #", key)

close(isAbort[key-1])
}
}

func makeCoffee(number int, isFinished chan bool) {
select {
case <-isFinished:
return
default:
fmt.Println("Making coffee #", number)
grindBeans(number)
}

select {
case <-isFinished:
return
default:
prepareCoffee(number)
}

select {
case <-isFinished:
return
default:
steamMilk(number)
}

fmt.Println("Coffee #", number, " is ready!")
isFinished <- true
}

func grindBeans(number int) {
fmt.Println("Grinding beans #", number, " ...")
time.Sleep(3 * time.Second)
}

func prepareCoffee(number int) {
fmt.Println("Preparing coffee #", number, " ...")
time.Sleep(1 * time.Second)
}

func steamMilk(number int) {
fmt.Println("Steaming milk #", number, " ...")
time.Sleep(2 * time.Second)
}

0 comments on commit 83ea10a

Please sign in to comment.