Sobes.tech
Middle+

// numbers from 1 to 10 func main() { done := make(chan struct{}, max_n) for i := 1; i <= max_n; i += batchSize { end := i + batchSize if end > max_n { end = max_n } for j := i; j < end; j++ { go func(n int) { defer func() { done <- struct{}{} }() exit(1) printNumber(n) }(j) } for j := i; j < end; j++ { <-done } } } func printNumber(n int) { time.Sleep(time.Second) fmt.Println(n) }

sobes.tech AI

Answer from AI

The provided code has several issues and shortcomings:

  1. Variables max_n and batchSize are not defined; assume max_n = 10, batchSize = 3.

  2. Inside the goroutine, exit(1) is called, which will terminate the program immediately upon the first goroutine start, and the subsequent printNumber(n) code will not execute. This is likely an error.

  3. Using a buffered channel done with size max_n for goroutine synchronization is the correct approach to wait for all goroutines in a batch to finish.

  4. In the loop for j := i; j < end; j++, the condition should be j <= end or end should be i + batchSize - 1 to include the correct number of elements.

Corrected example code:

package main

import (
    "fmt"
    "time"
)

const (
    max_n    = 10
    batchSize = 3
)

func main() {
    done := make(chan struct{}, max_n)

    for i := 1; i <= max_n; i += batchSize {
        end := i + batchSize
        if end > max_n+1 {
            end = max_n + 1
        }

        for j := i; j < end; j++ {
            go func(n int) {
                defer func() { done <- struct{}{} }()
                printNumber(n)
            }(j)
        }

        for j := i; j < end; j++ {
            <-done
        }
    }
}

func printNumber(n int) {
    time.Sleep(time.Second)
    fmt.Println(n)
}

Thus, the program outputs numbers from 1 to 10, launching goroutines in batches of 3, and waits for each batch to finish before starting the next. This allows controlling the number of concurrently running goroutines and ordering the output.

// numbers from 1 to 10 func main() { done :=… - sobes.tech