1. 6
  1.  

  2. 1

    Very cool, I was just going to play around with execution modes next week too!

    Any ideas if there are any gotchas regarding linking things that rely on Go’s runtime like goroutines?

    1. 2

      None of this new stuff is really well documented at this point (so forgive me if I make a mistake) but as I understand it, the runtime is spawned on its own thread(s) the first time the library is called into, package init runs (but main is not executed), and then the called function is executed. The runtime will manage goroutines across threads (‘P’s in the runtime nomenclature) like normal, and these continue executing independently of Rust threads. I also have a hunch that each time Rust makes a Go call, some kind of thread context switch is required so that the function can be called on a new 'G’ (goroutine) the same way it currently works when Go code makes a C call using cgo.

      I did get a simple toy program running that used a channel returned by Go to receive integers and print them from Rust. I added the following Go functions:

      //export CounterTo
      func CounterTo(max int) <-chan int {
              c := make(chan int)
              go func() {
                      for i := 0; i < max; i++ {
                              c <- i
                      }
              }()
              return c
      }
      
      //export RecvInt
      func RecvInt(<-chan int) int {
              return <-c
      }
      

      And here was the Rust code: http://sprunge.us/jUVi

      All of the usual memory management caveats apply. Memory allocated by Go cannot be safely passed across the C boundary without retaining a reference to prevent it from being collected and causing a use-after-free. I made this mistake with my channel example (and it’s a good thing I had not pushed that code yet), since the counter goroutine would exit after the max was reached and the channel could be collected, making recv unsafe to call on the Rust side.

      Another bummer for me is that these new execution modes only seem to be supported on linux/amd64. This is unfortunate in my case, as I had wanted to use this to integrate Go code into a .NET Windows GUI application. Since I believe Go 1.5 is in feature freeze at this point, something like this may have to wait until 1.6 or later.

      1. 1

        That’s very informative, thank you!