Speeding up select

272 views
Skip to first unread message

carloalber...@gmail.com

unread,
May 27, 2020, 9:00:47 PM5/27/20
to golang-dev
I am experimenting with generalizing the single-channel select optimizations done by the compiler to multiple channels. 

A quick prototype implemented in the runtime looks promising, but before spending too much time on it (there's one regression that needs work) I wanted to ask for help in understanding if the approach is, in general, ok from the perspective of the language spec.

I tried to ask on gophers slack, but we could not find a good argument as to why this shouldn't be allowed.

The gist of the idea is to try to avoid locking all channels, if we detect that any of the channels is ready and can proceed.

For this though it requires the following transformations to be allowed by the spec. Anybody knows?

non-blocking case

select {
case <-f1():
case <-f2():
default:
  // body default
}

transformed into (randbool returns a pseudorandom uniform bool value)

c1, c2 := f1(), f2()
if randbool() {
  c1, c2 = c2, c1
}
select {
case <-c1:
default:
  select {
  case <-c2:
  default:
    // body default
  }
}

blocking case 

select {
case <-f1():
case <-f2():
}

transformed into

c1, c2 := f1(), f2()
if randbool() {
  c1, c2 = c2, c1
}
select {
case <-c1:
default:
  select {
  case <-c2:
  default:
    select {
    case <-c1:
    case <-c2:
    }
  }
}

The one I'm least confident about is the non-blocking case, as I'm specifically not sure whether picking the default case in that way is correct. This could possibly be a safer, but slower, approach:

c1, c2 := f1(), f2()
if randbool() {
  c1, c2 = c2, c1
}
select {
case <-c1:
default:
  select {
  case <-c2:
  default:
    select {
    case <-c1:
    case <-c2:
    default:
      // body default
    }
  }
}

Thoughts?

Carlo Alberto

Keith Randall

unread,
May 27, 2020, 9:55:53 PM5/27/20
to carloalber...@gmail.com, golang-dev
You might want to peruse https://go-review.googlesource.com/c/go/+/7570. It was a more general version of what you're proposing. We ended up not going with it - lots of scary and subtle interactions with memory model, etc.



--
You received this message because you are subscribed to the Google Groups "golang-dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-dev+...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-dev/aa0f62a0-6c1f-4ffa-8a38-1e9dce388ecd%40googlegroups.com.

ca...@mercari.com

unread,
May 28, 2020, 7:12:59 PM5/28/20
to golang-dev
Great, one the comments answers my question. Will drop the default case, and try to make sure there are no regressions.
To unsubscribe from this group and stop receiving emails from it, send an email to golan...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages