看 GOPl 那本蓝皮书时,第九章讲共享变量,其中讲到 sync.Mutex 是不可重入的,已经获得 Lock 的 goroutine 重复调用 Lock,也会阻塞。然后 9.2 节(英文版 265 页)有下面这段话:
There is a good reason Go's mutexes are not re-entrant. The purpose of a mutex is to ensure that certain invariants of the shared variables are maintained at critical points during program execution. One of the invariants is "no goroutine is accessing the shared variables", but there may be additional invariants specific to the data structures that the mutex guards. When a goroutine acquires a mutex lock, it may assume that the invirants hold. While it holds the lock, it may update the shared variables so that the invariants are temporarily violated. However, when it releases the lock, it must guarantee that the order has been restored and the invariants hold once again. Although a re-entrant mutex would ensure that no other goroutines are accessing the shared variables, it cannot protect the additional invariants of those variables.
读了很多遍还是觉得难以理解,invariants 应该是某些不变的属性,不变量的意思,但是原文所说的除了“没有其他 goroutine 访问这个变量”这个 invariant 之外,mutex 保护的还有别的 invariant 。具体是指什么有前辈指点下?
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.