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
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.