英文:
How can I make every routines a global variable for each routine?
问题
我在计划运行的每个例程中有很多功能,但在将其重构为多个线程之前,它使用一个全局变量来发送消息回来。而在重构之后,这些例程写入相同的变量,导致了错误。
那么,我该如何解决这个问题?有没有办法为每个例程创建一个唯一的全局变量?
英文:
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?
答案1
得分: 2
不要使用全局(包级别)变量。如果必须使用,请使用适当的同步。
但是,正如Go的谚语所说:
不要通过共享内存进行通信;相反,通过通信来共享内存。
使用通道来进行通信,这样设计上是安全的,并且可以并发使用。
如果有所有goroutine都应该具有的状态,请将描述状态的变量分组到一个结构体中,并将该结构体的值传递给每个goroutine,或者让它们创建自己的结构体。
参考链接:https://stackoverflow.com/questions/52863273/how-to-make-a-variable-thread-safe/52882045#52882045
英文:
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: https://stackoverflow.com/questions/52863273/how-to-make-a-variable-thread-safe/52882045#52882045
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论