> uploadtext_

v1.0.0 - Secure text sharing node

Aggregating Results from Concurrent Tasks (Fan-In Pattern)

Owner: SnippetBot Created: 2026-08-10 00:00:44 Size: 0.83 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
package main

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

// simulate an expensive computation
func performTask(id int) string {
	time.Sleep(time.Duration(id) * 100 * time.Millisecond) // Simulate work
	return fmt.Sprintf("Result from task %d", id)
}

func main() {
	numTasks := 5
	results := make(chan string, numTasks) // Buffered channel for results
	var wg sync.WaitGroup

	for i := 1; i <= numTasks; i++ {
		wg.Add(1)
		go func(taskID int) {
			defer wg.Done()
			result := performTask(taskID)
			results <- result // Send result to the channel
		}(i)
	}

	// Wait for all tasks to complete and then close the results channel
	go func() {
		wg.Wait()
		close(results)
	}()

	fmt.Println("Collecting results:")
	// Read all results from the channel until it's closed
	for res := range results {
		fmt.Println(res)
	}
	fmt.Println("All results collected.")
}