0

Looking to make some code as multi-core friendly as possible via frequent use of go-routines. However, I'm new with golang and missing something apparently basic.

As way of example, I'd like to spawn a go-routine that creates and holds open an rpc communciation channel to an altcoin wallet. Skipping a bunch of irrelavent stuff, the code looks something like:

package wallet
var client btcprcclient.Client
func Server(c chan int) {
    client, err := bitrpcclient.New()  
    defer client.Shutdown() 
    c <- 1 // signal main routine client is establish
    <- c   // wait for the main routine to signal us to shutdown
}

func Status() {
    blockCount, err := client.GetBlockCount()
}

package main
func main() {
    c := make(chan int)
    go wallet.Server(c)
    <- c // wait for the wallet to be ready
    wallet.Status()
    c <-1 // terminate the wallet connection
} 

If I append the code in the Status() function into the Server() function it works fine. However as pseudo-written, I get an invalid memory address panic when Status() references the global-to-wallet client variable.

I guessing the "right" way of doing this is to rewrite Server to act on channel input, calling a local status() function (and/or anything else I wanted to do with the wallet), but my mind is confused on why the current way doesn't work. Even if main() & Status() run on core 0, and Server runs on core 1, the box still has a common memory model, so the var client's address should be the same???

Cassey
  • 118
  • 9
  • 2
    `client, err := bitrpcclient.New()` shadows the global `var client btcprcclient.Client`. you have to change it to `client, err = ...` – ymonad Feb 02 '17 at 02:28
  • 1
    and same question here: http://stackoverflow.com/questions/34195360/golang-how-to-use-global-var-across-files-in-a-package – ymonad Feb 02 '17 at 02:29
  • Thanks! Of course, I had to add a `var err error` definition once I made it an assignment, but that did the trick! For anyone trying to use this, it should also have been `var client *btcrpcclient.Client`. – Cassey Feb 02 '17 at 02:53

0 Answers0