CodeBlanks Logo Icon CodeBlanks

Job queue

Distribute jobs to workers over a channel.

Job queue and dispatch

The code sending jobs (the producer) runs in its own goroutine and closes the channel when done. Closing signals "no more jobs" to the workers; their range loops end by themselves.

go func() {
    for i, yol := range dosyalar {
        isler <- Is{ID: i, Yol: yol}
    }
    close(isler)
}()

Only the sending side closes a channel; the receiving side doesn't.

Buffer size

Giving the job channel a small buffer (make(chan Is, 100)) lets the producer run a bit ahead of the workers and smooths short waits. But a buffer isn't a concurrency fix; a correct program must also work unbuffered. A huge buffer consumes memory and hides backpressure.

Practice Dispatch

In a separate goroutine send the files []string{"a", "bb", "ccc"} to the isler channel and close it. Three workers send the length of each path to sonuclar. main reads the three results and prints the total.

Starter code

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import "fmt"

func main() {
    dosyalar := []string{"a", "bb", "ccc"}
    isler := make(chan string)
    sonuclar := make(chan int)
    for w := 0; w < 3; w++ {
        go func() {
            for yol := range isler {
                sonuclar <- len(yol)
            }
        }()
    }
    go func() {
        for _, d := range dosyalar {
            isler <- d
        }
        close(isler)
    }()
    toplam := 0
    for i := 0; i < len(dosyalar); i++ {
        toplam += <-sonuclar
    }
    fmt.Println(toplam)
}

Expected output

6

Questions and answers

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

1 Why does the producer run in its own goroutine?

  • Because closing a channel requires it
  • To catch errors
  • So sending on an unbuffered channel doesn't deadlock before results are read Correct answer
  • So it compiles faster

Explanation: If main both sends and reads results, workers may wait on the result channel while main waits on the job channel; a separate producer breaks this cycle.

2 Signal

Question
for _, is := range liste {
    isler <- is
}
____(isler)
Answer
for _, is := range liste {
    isler <- is
}
close(isler)

Explanation: close(isler) ends the workers' range loops.

3 Who does what?

Term Meaning
Producer Sends jobs and closes
Worker Reads with range
Arabellek Smooths short waits
close "No more jobs" signal

All lessons in Intermediate