Write a concurrent Golang program to count the total number of letters in a given paragraph.
As we outlined in the previous chapter, the first thing to tackle in the solution is to identify the core function that we would like to run concurrently.
Now, let’s write this
package main import ( "fmt" "unicode/utf8" ) func countLetters(s string, c chan int) { c <- utf8.RuneCountInString(s) } func main() { ch := make(chan int) word1 := "Hola" word2 := "Dias" go countLetters(word1, ch) letterCount1 := <-ch go countLetters(word2, ch) letterCount2 := <-ch fmt.Println("Total letters in", word1, letterCount1, word2, letterCount2) }
If you observe the above code closely, you can see anatomy of a loop. So, to complete the solution, we need to do the following:
Let’s take a look at the final solution in the below code:
package main import ( "fmt" "strings" "time" "unicode/utf8" ) func countLetters(s string, c chan int) { c <- utf8.RuneCountInString(s) } func main() { ch := make(chan int) totalCount := 0 start := time.Now() fmt.Println("start", start) myParagraph := "All the world is a stage" myParagraphs := "" for i := 0; i < 1000; i++ { myParagraphs += " " + myParagraph } words := strings.Fields(myParagraphs) for _, word := range words { go countLetters(word, ch) totalCount += <-ch } fmt.Println("Total letters: ", totalCount) fmt.Println("end", time.Since(start)) }
In the above example,
totalCount
variable.RELATED TAGS
CONTRIBUTOR
View all Courses