Skip to content

Commit d647be8

Browse files
committed
Refactor fish demo with mutex.synchronize with block
1 parent 90ddeb3 commit d647be8

File tree

1 file changed

+13
-16
lines changed
  • ruby/producer-consumer-model

1 file changed

+13
-16
lines changed

ruby/producer-consumer-model/fish.rb

Lines changed: 13 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
# ref: https://jyywiki.cn/OS/2023/build/lect9.ipynb
44

55
# Q: what's the difference between `MUTEX.lock {}` and `MUTEX.lock + MUTEX.unlock` ?
6+
# A: it should be `MUTEX.synchronize {}`
67
# Q: what's the meaning of @quota?
78

89
FSM = [
@@ -34,26 +35,22 @@ def can_print?(event)
3435
end
3536

3637
def fish_before(event)
37-
MUTEX.lock
38-
39-
while !can_print?(event) do
40-
COND_VAR.wait(MUTEX)
38+
MUTEX.synchronize do
39+
while !can_print?(event) do
40+
COND_VAR.wait(MUTEX)
41+
end
42+
@quota -= 1
4143
end
42-
@quota -= 1
43-
44-
MUTEX.unlock
4544
end
4645

4746
def fish_after(event)
48-
MUTEX.lock
49-
50-
@quota += 1
51-
@current_state = next_state(event)
52-
# assert @current_state
53-
raise "invalid transition, current_state: #{@current_state}, event: #{event}" if @current_state.nil?
54-
COND_VAR.broadcast
55-
56-
MUTEX.unlock
47+
MUTEX.synchronize do
48+
@quota += 1
49+
@current_state = next_state(event)
50+
# assert @current_state
51+
raise "invalid transition, current_state: #{@current_state}, event: #{event}" if @current_state.nil?
52+
COND_VAR.broadcast
53+
end
5754
end
5855

5956
def fish_thread(char)

0 commit comments

Comments
 (0)