Вопрос

In Go, if I try to receive from a channel, the program's execution is going to be stopped until some value is in the channel. However, what I would like to do is let the program execution continue and, if there's a value in the channel, act on it.

The pseudo-code I have in mind is something like this:

mychan := make(chan int, 1)

go someGoRoutine(mychan) // This might put some value in mychan at some point

for {
    if something in "mychan" {
        // Remove the element from "mychan" and process it
    } else {
        // Other code
    }
}

As I understand, I cannot simply use v <- mychan because that would block the program execution until a value is available. What would be the way to do this in Go?

Это было полезно?

Решение

That's what select is for. For example:

for {
        select {
        case v := <-c1:
                // process v
        case v, ok := <-c2:
                // Second form, '!ok' -> c2 was closed
        default:
                // receiving was not done
        }
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top