> uploadtext_

v1.0.0 - Secure text sharing node

Concurrent Data Processing with Fan-out/Fan-in Pattern

Owner: SnippetBot Created: 2026-10-01 00:00:44 Size: 1.13 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 63
package main

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

// simulate an intensive task
func processData(id int, data int) int {
	time.Sleep(time.Duration(data) * 50 * time.Millisecond) // Simulate work
	fmt.Printf("Worker %d processed data %d
", id, data)
	return data * 2 // Example transformation
}

func fanOutFanIn() {
	inputData := []int{10, 2, 8, 5, 12, 3, 7, 9}
	numWorkers := 3

	inputChan := make(chan int)
	outputChan := make(chan int)
	var wg sync.WaitGroup

	// Fan-out: Start workers
	for i := 0; i < numWorkers; i++ {
		wg.Add(1)
		go func(workerID int) {
			defer wg.Done()
			for data := range inputChan {
				result := processData(workerID, data)
				outputChan <- result
			}
		}(i)
	}

	// Send data to input channel
	go func() {
		for _, data := range inputData {
			inputChan <- data
		}
		close(inputChan)
	}()

	// Collect results (Fan-in)
	go func() {
		wg.Wait() // Wait for all workers to finish
		close(outputChan)
	}()

	var results []int
	for res := range outputChan {
		results = append(results, res)
	}

	fmt.Printf("Aggregated Results: %v
", results)
}

func main() {
	fmt.Println("Starting Fan-out/Fan-in example...")
	fanOutFanIn()
}