Skip to content

Commit f73f1ca

Browse files
committed
update sema
1 parent b22a0fc commit f73f1ca

File tree

1 file changed

+21
-23
lines changed

1 file changed

+21
-23
lines changed

semaphore.md

Lines changed: 21 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,16 @@
11
# Semaphore
22

33
```go
4-
// Semaphore implementation exposed to Go.
5-
// Intended use is provide a sleep and wakeup
6-
// primitive that can be used in the contended case
7-
// of other synchronization primitives.
8-
// Thus it targets the same goal as Linux's futex,
9-
// but it has much simpler semantics.
4+
// Go 语言中暴露的 semaphore 实现
5+
// 具体的用法是提供 sleep 和 wakeup 原语
6+
// 以使其能够在其它同步原语中的竞争情况下使用
7+
// 因此这里的 semaphore 和 Linux 中的 futex 目标是一致的
8+
// 只不过语义上更简单一些
109
//
11-
// That is, don't think of these as semaphores.
12-
// Think of them as a way to implement sleep and wakeup
13-
// such that every sleep is paired with a single wakeup,
14-
// even if, due to races, the wakeup happens before the sleep.
10+
// 也就是说,不要认为这些是信号量
11+
// 把这里的东西看作 sleep wakeup 实现的一种方式
12+
// 每一个 sleep 都会和一个 wakeup 配对
13+
// 即使在发生 race 时,wakeup sleep 之前时也是如此
1514
//
1615
// See Mullender and Cox, ``Semaphores in Plan 9,''
1716
// http://swtch.com/semaphore.pdf
@@ -24,18 +23,14 @@ import (
2423
"unsafe"
2524
)
2625

27-
// Asynchronous semaphore for sync.Mutex.
28-
29-
// A semaRoot holds a balanced tree of sudog with distinct addresses (s.elem).
30-
// Each of those sudog may in turn point (through s.waitlink) to a list
31-
// of other sudogs waiting on the same address.
32-
// The operations on the inner lists of sudogs with the same address
33-
// are all O(1). The scanning of the top-level semaRoot list is O(log n),
34-
// where n is the number of distinct addresses with goroutines blocked
35-
// on them that hash to the given semaRoot.
36-
// See golang.org/issue/17953 for a program that worked badly
37-
// before we introduced the second level of list, and test/locklinear.go
38-
// for a test that exercises this.
26+
// 为 sync.Mutex 准备的异步信号量
27+
28+
// semaRoot 持有一棵 地址各不相同的 sudog(s.elem) 的平衡树
29+
// 每一个 sudog 都反过来指向(通过 s.waitlink)一个在同一个地址上等待的其它 sudog 们
30+
// 同一地址的 sudog 的内部列表上的操作时间复杂度都是 O(1)。顶层 semaRoot 列表的扫描
31+
// 的时间复杂度是 O(log n),n 是被哈希到同一个 semaRoot 的不同地址的总数,每一个地址上都会有一些 goroutine 被阻塞。
32+
// 访问 golang.org/issue/17953 来查看一个在引入二级列表之前性能较差的程序样例,test/locklinear.go
33+
// 中有一个复现这个样例的测试
3934
type semaRoot struct {
4035
lock mutex
4136
treap *sudog // root of balanced tree of unique waiters.
@@ -439,6 +434,10 @@ func (root *semaRoot) rotateRight(y *sudog) {
439434
}
440435
}
441436

437+
```
438+
439+
440+
```go
442441
// notifyList is a ticket-based notification list used to implement sync.Cond.
443442
//
444443
// It must be kept in sync with the sync package.
@@ -611,5 +610,4 @@ func notifyListCheck(sz uintptr) {
611610
func sync_nanotime() int64 {
612611
return nanotime()
613612
}
614-
615613
```

0 commit comments

Comments
 (0)