Back to code Go

Procesar veinte tareas con cuatro trabajadores

Un pool de goroutines con canales: concurrencia con tope, sin lanzar una rutina por tarea.

This post is not in your language yet; you are seeing it in Spanish. The code is the same.

The problem

Hay que procesar muchos pedidos que tardan (una llamada, un archivo). Uno por uno es lento; todos a la vez tumba al servicio del otro lado. Hace falta un número fijo de trabajadores.

Go
package main

import (
	"fmt"
	"sync"
	"time"
)

func procesar(id int) string {
	time.Sleep(100 * time.Millisecond) // simula trabajo: una llamada, un archivo
	return fmt.Sprintf("pedido %d listo", id)
}

func main() {
	trabajos := make(chan int)
	resultados := make(chan string)
	var wg sync.WaitGroup

	for w := 0; w < 4; w++ { // cuatro trabajadores, no uno por pedido
		wg.Add(1)
		go func() {
			defer wg.Done()
			for id := range trabajos {
				resultados <- procesar(id)
			}
		}()
	}

	go func() {
		for id := 1; id <= 20; id++ {
			trabajos <- id
		}
		close(trabajos)
		wg.Wait()
		close(resultados)
	}()

	for r := range resultados {
		fmt.Println(r)
	}
}

Why it is written this way

  1. Los cuatro trabajadores leen del mismo canal: Go reparte cada pedido a quien esté libre.
  2. Cerrar el canal de trabajos es la señal de "no hay más": cada for range termina solo.
  3. El WaitGroup espera a que los cuatro terminen antes de cerrar resultados; cerrarlo antes haría entrar en pánico al programa.
  4. Veinte tareas de 100 ms tardan medio segundo en vez de dos.
How to try it

Guardalo como main.go y corré: go run main.go. Cambiá el 4 por 1 y por 20 para ver la diferencia de tiempo.

Watch out

Los resultados llegan en el orden en que terminan, no en el que entraron. Si el orden importa, mandá el índice junto con el resultado y ordená al final.

Adapt it to your case with AI

The button copies this prompt with the code pasted below it. Replace the brackets with your own details and paste it into ChatGPT, Claude, Gemini or Copilot.

The prompt
Tengo este pool de trabajadores en Go. Adaptalo para que cada tarea sea [QUÉ HACE CADA TAREA], propague errores sin detener a las demás, respete un context con tiempo límite de [SEGUNDOS] segundos y devuelva los resultados en el orden original. Explicame en tres líneas cómo elegir el número de trabajadores para mi caso.

Example written and reviewed by hand.

Share

Comments

No comments yet. Yours can be the first.

Plain text only, no links. No email is requested. Comments are reviewed before they are published.

Did you adapt it to something of yours?

Tell me what you solved with it, or what it was missing.

Keep trying

More code

See all
Darinel Ortega Online · I reply during the day
Today
Hello. I'm not selling anything here: this is for exchanging knowledge about technology.
Write whatever you like — you can send text, images or documents. Messages reach my console and I reply from there.
You are writing outside working hours. I will read you as soon as the day starts.

An open conversation to share knowledge. Messages reach my console and I reply from there.

Let us book a conversation

Pick the day and time that work for you. Thirty minutes, no sales pitch.

Video call

For a video call, just ask for one here and I'll send you the session link.