-1

I have a lot of functions in every routines I'm planning to run, but before I reconstruct it to multiple threads, it uses a global variable to send message back. And after I reconstruct it, the routines write the same variable which causes panic.

So, how could I solve this problem? Is there a way to make a unique global variable for every routine?

Matt Kevin
  • 19
  • 3

1 Answers1

2

Don't use global (package level) variables. If you must, use proper synchronization.

But instead as Go's proverb goes:

Do not communicate by sharing memory; instead, share memory by communicating.

Use channels instead to communicate results which is safe for concurrent use by design.

If there is state all goroutines should have, group the variables describing the state into a struct, and pass a value of that struct to each goroutine, or have them create their own.

See related: How to make a variable thread-safe

icza
  • 389,944
  • 63
  • 907
  • 827
  • Thank you, the price of reconstruct antlr4-runtime is just too high. I'll try use channel to send message back then. Thanks a lot! – Matt Kevin Jul 30 '21 at 11:45