如何将每个例程都变成每个例程的全局变量?

huangapple go评论75阅读模式
英文:

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

huangapple
  • 本文由 发表于 2021年7月30日 18:04:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/68589124.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定