#homework help

30 messages · Page 1 of 1 (latest)

final warren
#

up

gusty raptor
gusty raptor
#

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

random sedge
#

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

gusty raptor
#

Wait, are you trying to say there's a potential runtime where a <- 1 doesn't consider 1 to be ready?

random sedge
#

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.

random sedge
gusty raptor
#

That would be fine though, it would just block until it is

#

(we're totally trampling over this homework assignment rofl)

#

Poor kid

random sedge
#

no, because there is a default clause in the select

gusty raptor
#

Ahhh

#

I understand now, sorry

random sedge
#

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

blissful venture
#

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

final warren
#

I tried that and I didn't understand it at first too xD

blissful venture
blissful venture
#
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
random sedge
#

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