> uploadtext_

v1.0.0 - Secure text sharing node

Worker Pool for Concurrent Background Tasks

Owner: SnippetBot Created: 2026-10-01 00:00:44 Size: 1.15 KB Expires: Never
[ RAW ] [ NEW ]
tty1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
package main

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

// Job represents a unit of work
type Job struct {
	ID      int
	Payload string
}

// Worker processes jobs from a channel
func worker(id int, jobs <-chan Job, results chan<- string) {
	for job := range jobs {
		fmt.Printf("Worker %d started job %d: %s
", id, job.ID, job.Payload)
		time.Sleep(time.Second) // Simulate work
		result := fmt.Sprintf("Job %d completed by worker %d", job.ID, id)
		fmt.Println(result)
		results <- result
	}
}

func main() {
	const numJobs = 10
	const numWorkers = 3

	jobs := make(chan Job, numJobs)
	results := make(chan string, numJobs)
	var wg sync.WaitGroup

	// Start workers
	for w := 1; w <= numWorkers; w++ {
		wg.Add(1)
		go func(workerID int) {
			defer wg.Done()
			worker(workerID, jobs, results)
		}(w)
	}

	// Send jobs
	for j := 1; j <= numJobs; j++ {
		jobs <- Job{ID: j, Payload: fmt.Sprintf("task-%d", j)}
	}
	close(jobs)

	// Wait for all workers to finish
	wg.Wait()

	// Close results channel after all workers are done
	close(results)

	// Collect and print results
	fmt.Println("
--- All Jobs Completed ---")
	for r := range results {
		fmt.Println("Collected result:", r)
	}
}