我有一个名为 Setter 的接口(interface)。 Struct called SetterImpl实现了这个接口(interface),有2个setter,都设置了2个接口(interface)。
type Setter interface {
A() *AInterface
B() *BInterface
}
type SetterImpl struct {
a *AInterface
b *BInterface
}
func (s *SetterImpl) A(a *AInterface) {
a = a
}
func (s *SetterImpl) B(b *AInterface) {
b = b
}
func returnSetter(a *AInterface, b *BInterface) Setter {
return &SetterImpl{a:a, b:b}
}
上述方法返回的 setter 在堆(比如 SHeap)中并发送到 gRPC 服务器。现在,我想更新 SetterImpl 中的 a 和 b,以便 gRPC 服务器使用新值。
所以我现在有 2 个 goroutines;一个是 gRPC 服务器主 goroutine(比如 MAIN),另一个是 fork 的 goroutine(比如 FORKED),它只是更新 setter 字段。
如果我在 FORKED 中使用 Mutex,那实际上是添加了一个栅栏(就像 java)。它实际上不锁定任何变量(除了它自己)。 我不希望 MAIN 能够在 FORKED 更新它们时读取存储在 SHeap 中的 a 和 b。服务器中的 API 线程(goroutines)在读取 SHeap 中的值之前不会获取 Read Mutex。那么,是否有可能实现我想要实现的目标?如果是,我该如何实现?
最佳答案
我不认为你可以在 Go 中锁定变量。您只能锁定一个代码段。
m.Lock()
// do stuff
m.Unlock()
通过使用“接口(interface)”与“实现”模式,您正在无中生有地为自己制造问题。
只需使用常规函数,您就可以让生活变得更简单。然后你可以把锁放在一个函数中,并保证它会受到保护。
既然你是在做一个接口(interface),你就不能保证实现接口(interface)的函数的内容是什么。
关于go - 在golang中获取内存地址而不是变量的锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55785524/