Skip to content

Commit

Permalink
lec12-p2
Browse files Browse the repository at this point in the history
  • Loading branch information
xyongcn authored Nov 17, 2024
1 parent 317c3c0 commit fc616c3
Showing 1 changed file with 119 additions and 2 deletions.
121 changes: 119 additions & 2 deletions lec12/p2-semaphore.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ backgroundColor: white
- 早期的操作系统的主要同步机制
![w:700](figs/basic-syncmutex.png)

<!--
Dijkstra 应译作“戴克斯特拉”
https://zhuanlan.zhihu.com/p/73390180
维基百科 Edsger Wybe Dijkstra 页面(https://en.wikipedia.org/wiki/Edsger_W._Dijkstra),Dijkstra 可读作 /ˈdaɪkstrə/ 或 [ˈdɛikstra]
-->
---

### 信号量(semaphore)
Expand All @@ -56,16 +61,128 @@ backgroundColor: white
- 线程不会被无限期阻塞在P()操作
- 假定信号量等待按先进先出排队

自旋锁能否实现先进先出?
**问题**自旋锁能否实现先进先出?

![bg right:30% 100%](figs/sema-train.png)


---

### 信号量在概念上的实现

<!--
![w:1200](figs/semaphore-impl.png)
-->

<font size=6>

```
Class Semaphore {
int sem;
WaitQueue q;
}
```

<style>
.container{
display: flex;
}
.col {
flex: 1;
}
</style>

<div class="container">

<div class="col">

```c++
Semaphore::P() {
sem--;
if (sem < 0) {
Add this thread t to q;
block(t)
}
}
```

</div>

<div class="col">

```c++
Semaphore::V() {
sem++;
if (sem <= 0) {
Remove a thread t from q;
wakeup(t)
}
}
```

</div>

</div>

</font>

---


### 信号量在概念上的实现

<font size=6>

```
Class Semaphore {
int sem;
WaitQueue q;
}
```

<style>
.container{
display: flex;
}
.col {
flex: 1;
}
</style>

<div class="container">

<div class="col">

```c++
Semaphore::P() {
while (sem <= 0) {
Add this thread t to q;
block(t)
}
sem--;
}
```

</div>

<div class="col">

```c++
Semaphore::V() {
sem++;
if (sem <= 0) {
Remove a thread t from q;
wakeup(t)
}
}
```

</div>

</div>

问题:这个实现与上一个有什么不同?

</font>

---

Expand Down

0 comments on commit fc616c3

Please sign in to comment.