package main import ( "fmt" "time" ) // simulateLongRunningOperation simulates a task that might take a while. // It sends a result on the 'result' channel after a random delay. func simulateLongRunningOperation(result chan<- string, id int) { delay := time.Duration(id%3+1) * time.Second // 1, 2, or 3 seconds time.Sleep(delay) result <- fmt.Sprintf("Operation %d completed in %v", id, delay) } func main() { fmt.Println("Starting operation timeout demonstration...") for i := 1; i <= 5; i++ { resultChan := make(chan string, 1) // Buffered channel for the result timeout := 2 * time.Second // Set a timeout of 2 seconds for each operation go simulateLongRunningOperation(resultChan, i) select { case res := <-resultChan: fmt.Printf(" Operation %d: %s ", i, res) case <-time.After(timeout): fmt.Printf(" Operation %d: TIMEOUT after %v! ", i, timeout) } time.Sleep(100 * time.Millisecond) // Small delay between tests } fmt.Println("Demonstration finished.") }