A goroutine starts a function concurrently with the rest of a Go program. Prefix a call with `go`, such as `go runTasks(&w)`, so `main` can continue starting the API while `runTasks` repeatedly checks the worker queue and runs pending tasks. section 5.6
The practical model is separation of responsibilities: request handlers accept requests and enqueue work, while a background goroutine performs task operations. This keeps the API from directly starting or stopping tasks and lets it remain available while work is processed. section 5.6
Use separate goroutines when independent worker activities must proceed together:
- Run a continuous queue-processing loop that invokes `RunTask` when work is available. section 5.6
- Periodically collect machine statistics with `w.CollectStats()`. section 7.5
- Start the API server concurrently rather than occupying the main goroutine. section 7.5
- Run an anonymous loop that periodically updates task information from workers while another loop reports task state. section 7.5
Worker components running together
A worker can launch queue processing, statistics collection, and API serving with three `go` calls. Each component then proceeds concurrently: the task loop sleeps between polls, stats collection runs periodically, and the API listens for requests. section 7.5 section 5.6
Listing 7.11 Running all the worker’s components in separate goroutines
func main() {
host := os.Getenv("CUBE_HOST")
port, _ := strconv.Atoi(os.Getenv("CUBE_PORT"))
fmt.Println("Starting Cube worker")
w := worker.Worker{
Queue: *queue.New(),
Db: make(map[uuid.UUID]*task.Task),
}
api := worker.Api{Address: host, Port: port, Worker: &w}
go runTasks(&w)
go w.CollectStats()
go api.Start()
This listing places each worker responsibility behind an explicit `go` call, making the concurrent structure visible before manager setup and task submission. section 7.5
This approach is deliberately operational rather than a full treatment of goroutine internals. The important decision is which activities need to continue independently: task execution, machine-stat collection, API serving, and manager updates. section 5.6 section 7.5






