#homework help
30 messages · Page 1 of 1 (latest)
https://go.dev/ref/spec#Select_statements
If one or more of the communications can proceed, a single one that can proceed is chosen via a uniform pseudo-random selection.
No, you can pass anything into a channel
a <- 1 passes 1 into the channel a
Since both 1 and 2 are being passed at the same time, it randomly chooses one
but there is a default, which always occurs if no case is ready to proceed
so whether this prints 3 never, with equal frequency, or always depends on details of the runtime
Wait, are you trying to say there's a potential runtime where a <- 1 doesn't consider 1 to be ready?
in an idealized execution model, i would expect equal frequency. with a single processor, always printing 3 would probably be the conclusion of hoare semantics.
there's a potential runtime where a <- 1 doesn't consider <-a on the other end to be ready, yes
That would be fine though, it would just block until it is
(we're totally trampling over this homework assignment rofl)
Poor kid
no, because there is a default clause in the select
if a <- 1 is not ready, then a <- 2 is not ready for the same reason, so the default happens
which does block on a <- 3
I propose simple answer
Why to guess
When u can run and see for yourself 🙂
Add code for 1000+ invocation of it and calculate times which numbers happened
Let compiler judge it, it was made for this xD
But the their question is other thing
I tried that and I didn't understand it at first too xD
hehe. All right.
some people above voiced that even 3 would be invoked though
package main
import (
"fmt"
"os"
"os/exec"
"strings"
)
func S(a chan int) {
go func() {
select {
case a <- 1:
case a <- 2:
default:
a <- 3
}
}()
fmt.Println(<-a)
}
func Run() {
msg := make(chan int)
S(msg)
}
func main() {
if len(os.Args) < 2 {
Run()
return
}
counts := make(map[string]int)
for i := 0; i < 100; i++ {
key, _ := exec.Command(
"go",
"run",
".",
).CombinedOutput()
number := strings.TrimSpace(string(key))
if _, ok := counts[number]; !ok {
counts[number] = 0
}
counts[number]++
}
for key, element := range counts {
fmt.Println("Key:", key, "=>", "Counts:", element)
}
}
always 1 or 2 with around 50% chance
$ go run . loop
Key: 1 => Counts: 43
Key: 2 => Counts: 57
$ go run . loop
Key: 2 => Counts: 500
Key: 1 => Counts: 500
the point is that nothing in the language spec or memory model requires that 3 can't happen, and indeed, with a bit of work in between, it starts to show up: https://go.dev/play/p/p3fuetOlubu