英文:
Golang: Values containing the types defined in this package should not be copied
问题
链接https://golang.org/pkg/sync/中指出:“不应复制包中定义的类型的值。”
为什么会这样?如果我忽略这个建议会发生什么?
英文:
The link https://golang.org/pkg/sync/ states "Values containing the types defined in this package should not be copied."
Why is it so? What would happen if I ignore the advice ?
答案1
得分: 4
这将不再起作为同步原语的作用。最好的情况是你会得到不可预测的行为。
想象一下锁(例如)就像是一个旗帜。如果锁定了,旗帜就被设置了。如果你复制这个锁(复制旗帜的状态),复制品会表现得好像它被锁定了,而实际上并没有。如果你解锁复制品,原始的锁并不会改变,所以它会表现得好像它被锁定了,而实际上它不应该再被锁定了。
英文:
It would simply not work as a synchronization primitive anymore. At best you would get unpredictable behavior.
Think of a lock (for instance) as a flag. If it is locked, the flag is set. If you copy that lock (you copy the flag's state), the copy would behave as if it was locked while it’s not. If you unlock the copy, the original won’t change so it will behave as if it was locked while it’s not supposed to be locked anymore.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论