Created
March 28, 2025 09:02
-
-
Save dacr/b3526e5cbf10acc8c47907b1b646c650 to your computer and use it in GitHub Desktop.
go channels select / published by https://github.com/dacr/code-examples-manager #686a22d1-9224-49ea-be72-1c8371cfc9f4/b9bc9db8efa12f47714594462867dc18894058ab
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*?sr/bin/true; exec /usr/bin/env nix-shell -p go --run "go run $0" #*/ | |
// summary : go channels select | |
// keywords : go, channels, @testable | |
// publish : gist | |
// authors : David Crosson | |
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2) | |
// id : 686a22d1-9224-49ea-be72-1c8371cfc9f4 | |
// created-on : 2025-03-27T16:43:12+01:00 | |
// managed-by : https://github.com/dacr/code-examples-manager | |
// run-with : nix-shell -p go --run "go run $file" | |
package main | |
import ( | |
"fmt" | |
"math/rand" | |
"time" | |
) | |
func main() { | |
ch1 := make(chan int, 1) | |
ch2 := make(chan int, 1) | |
go func() { | |
time.Sleep(time.Duration(10+rand.Intn(100)) * time.Millisecond) | |
ch1 <- 42 | |
}() | |
go func() { | |
time.Sleep(time.Duration(10+rand.Intn(100)) * time.Millisecond) | |
ch2 <- 43 | |
}() | |
select { | |
case v := <-ch1: | |
fmt.Println("Winner is channel 1", v) | |
case v := <-ch2: | |
fmt.Println("Winner is channel 2", v) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment