Sobes.tech
Senior

// Escribir un manejador asíncrono de tareas como una biblioteca // El cliente pasa un objeto (Task) con datos para realizar la tarea, // en nuestro ejemplo usaremos una estructura vacía. // El manejador puede procesar simultáneamente no más de N tareas, // y no más de X tareas pueden estar en cola para su procesamiento. // Si no hay espacio en la cola, se devuelve inmediatamente un error al cliente. // La tarea se procesa si hay procesadores libres disponibles. // Simulamos la duración del procesamiento con time.Sleep(5*time.Second). // Tan pronto como una tarea termina, tomamos la siguiente de la cola. // Si la cola está vacía, esperamos nuevas tareas de los clientes. // Con una estrella: ampliar la estructura Task y obtener los estados de las tareas mediante una consulta separada.

sobes.tech AI

Respuesta de la IA

go package taskhandler

import ( "errors" "sync" "time" )

type Task struct { ID int Status string // "queued", "processing", "done", "error" }

type Handler struct { maxWorkers int maxQueue int queue chan *Task wg sync.WaitGroup mu sync.Mutex tasks map[int]*Task workerSem chan struct{} idCounter int }

func NewHandler(maxWorkers, maxQueue int) *Handler { h := &Handler{ maxWorkers: maxWorkers, maxQueue: maxQueue, queue: make(chan *Task, maxQueue), tasks: make(map[int]*Task), workerSem: make(chan struct{}, maxWorkers), } go h.dispatch() return h }

func (h *Handler) Submit(task *Task) (int, error) { h.mu.Lock() defer h.mu.Unlock()

if len(h.queue) >= h.maxQueue {
	return 0, errors.New("queue is full")
}
h.idCounter++
task.ID = h.idCounter
task.Status = "queued"
h.tasks[task.ID] = task
h.queue <- task
return task.ID, nil

}

func (h *Handler) dispatch() { for task := range h.queue { h.workerSem <- struct{}{} // acquire worker slot h.wg.Add(1) go h.process(task) } }

func (h *Handler) process(task *Task) { defer func() { <-h.workerSem // release worker slot h.wg.Done() }()

// Обновляем статус
h.mu.Lock()
task.Status = "processing"
h.mu.Unlock()

// Имитация длительной обработки
time.Sleep(5 * time.Second)

// Завершение задачи
h.mu.Lock()
task.Status = "done"
h.mu.Unlock()

}

func (h *Handler) Status(taskID int) (string, error) { h.mu.Lock() defer h.mu.Unlock() if task, ok := h.tasks[taskID]; ok { return task.Status, nil } return "", errors.New("task not found") }

func (h *Handler) Shutdown() { close(h.queue) h.wg.Wait() }


Этот код реализует асинхронный обработчик задач с ограничением на количество одновременно обрабатываемых задач (maxWorkers) и размер очереди (maxQueue). Если очередь заполнена, Submit возвращает ошибку. Статусы задач можно получить через метод Status по ID задачи.