CodeBlanks Logo Icon CodeBlanks

Challenge 1 - Concurrency

Write a program combining goroutines, channels and WaitGroup.

Challenge: a parallel word counter

You will write a program that processes several texts at once and finds the total word count. Each text is counted in its own goroutine, the results are collected on a channel, and the end of all goroutines is awaited with a sync.WaitGroup.

metinler := []string{
    "go hızlı ve basit",
    "kanallar goroutine'leri bağlar",
    "eşzamanlılık paralellik değildir",
}
// expected total: 10

Use strings.Fields to count words; it handles multiple spaces and newlines correctly.

Plan

1) sonuc := make(chan int, len(metinler)) — a buffer with room for every goroutine. 2) For each text, wg.Add(1) + a goroutine: sonuc <- len(strings.Fields(m)). 3) wg.Wait(), then close(sonuc). 4) Sum with for n := range sonuc. Thanks to the buffer, Wait and close can safely happen in the same goroutine.

Practice Write the counter

Write the program following the plan and print the total word count.

Starter code

main.go
package main

import (
    "fmt"
    "strings"
    "sync"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "fmt"
    "strings"
    "sync"
)

func main() {
    metinler := []string{
        "go hızlı ve basit",
        "kanallar goroutine'leri bağlar",
        "eşzamanlılık paralellik değildir",
    }
    sonuc := make(chan int, len(metinler))
    var wg sync.WaitGroup
    for _, m := range metinler {
        wg.Add(1)
        go func(m string) {
            defer wg.Done()
            sonuc <- len(strings.Fields(m))
        }(m)
    }
    wg.Wait()
    close(sonuc)
    toplam := 0
    for n := range sonuc {
        toplam += n
    }
    fmt.Println(toplam)
}

Expected output

10

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How many elements does <code>strings.Fields(" a b ")</code> return?

  • 2 Correct answer
  • 5
  • 3
  • 7

Explanation: Fields treats consecutive spaces as one separator and drops leading/trailing spaces; Split(" ") would produce empty pieces.

2 Split the words

Question
n := len(strings.____(metin))
Answer
n := len(strings.Fields(metin))

Explanation: strings.Fields splits text into words by whitespace.

3 Piece and role

Term Meaning
goroutine Counts one text
The sonuc channel Carries the counts
wg.Wait Waits for all to finish
range sonuc Sums

All lessons in Intermediate