Skip to content

Commit f0d8efc

Browse files
Update p3-monitor-cond.md
1 parent a29e3e0 commit f0d8efc

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

lec12/p3-monitor-cond.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -398,3 +398,23 @@ https://yangzhaoyunfei.github.io/monitors/ 管程(Monitors) -->
398398
#### 生产者-消费者问题的管程实现
399399

400400
![w:1000](figs/monitor-pc-4.png)
401+
402+
403+
---
404+
#### 如何使用管程?
405+
406+
Java支持管程;C++支持条件变量
407+
408+
```
409+
public class CounterMonitor {
410+
private int count = 0; // 共享资源
411+
// 增加count的方法,这里用synchronized关键字确保互斥访问
412+
public synchronized void increment() {
413+
count++; // 可以添加其他逻辑,比如通知等待的线程等
414+
}
415+
// 获取count值的方法,也需要同步
416+
public synchronized int getCount() {
417+
return count;
418+
}
419+
}
420+
'''

0 commit comments

Comments
 (0)