awesome-patterns/concurrency/concurrency_in_go/ch1/letter_channel_example.go

58 lines
1.2 KiB
Go
Raw Normal View History

2018-01-06 19:04:06 +03:00
package ch1
import (
"fmt"
"strings"
)
var initialString string
var initialBytes []byte
var stringLength int
var finalString string
var lettersProcessed int
2018-01-08 15:30:16 +03:00
var applicationStatusL bool
2018-01-06 19:04:06 +03:00
func getLetters(gQ chan string) {
for i := range initialBytes {
gQ <- string(initialBytes[i])
}
}
func capitalizeLetters(gQ chan string, sQ chan string) {
for {
if lettersProcessed >= stringLength {
2018-01-08 15:30:16 +03:00
applicationStatusL = false
2018-01-06 19:04:06 +03:00
break
}
select {
case letter := <-gQ:
capitalLetter := strings.ToUpper(letter)
finalString += capitalLetter
lettersProcessed++
}
}
}
func RunLetter() {
2018-01-08 15:30:16 +03:00
applicationStatusL = true
2018-01-06 19:04:06 +03:00
getQueue := make(chan string)
stackQueue := make(chan string)
initialString = `Four score and seven years ago our fathers
brought forth on this continent, a new nation, conceived in
Liberty, and dedicated to the proposition that all men are
created equal.`
initialBytes = []byte(initialString)
stringLength = len(initialString)
lettersProcessed = 0
fmt.Println("Let's start capitalizing")
go getLetters(getQueue)
capitalizeLetters(getQueue, stackQueue)
close(getQueue)
close(stackQueue)
for {
2018-01-08 15:30:16 +03:00
if applicationStatusL == false {
2018-01-06 19:04:06 +03:00
fmt.Println("Done")
fmt.Println(finalString)
break
}
}
}