简体   繁体   中英

Running another instance of the same program with a goroutine?

Is it an acceptable practice to run multiple instances of the same go program using goroutines, like running go main()?

If so, is it possible to modify arguments sent to the goroutine (or os.Args[]) such that the main() function does not create an infinite number of goroutines? The goroutines should then be able to communicate with each other via channels. I understand that goroutines share the same memory space but have separate stacks, so this could cause some race condition issues.

Or, perhaps, this is an improper use of Goroutines and I should just stick to exec.Command() to execute another instance of the executable, and have those instances communicate via a JSON-RPC.

Thanks for the assistance.

I'm not sure you are understanding how a goroutine works here. Think of it like a virtual thread, as it is pretty much Go's alternative to threads in practice. When you call go foo() you are spawning a goroutine (or virtual thread) within your executable same as you would a thread in other languages, not a separate process as an exec or syscall.ForkExec().

The proper practice in Go is to stick with a single process and use goroutines for concurrent responsibilities. For example, if you are writing your own port listener and want several iterations to each listen on a different port, your outline might be:

func APIHandler(port int) {
    // do stuff
}

func main() {
    go APIHandler(80)
    go APIHandler(81)
    go APIHandler(82)

    // sync.WaitGroup, or maybe wait on an error chan
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM