Skip to content

Commit da98794

Browse files
committed
Avoid broadcast in Bounded_q benchmark
This should help to avoid the thundering herd problem and improve thruput.
1 parent adb1f6a commit da98794

File tree

1 file changed

+10
-3
lines changed

1 file changed

+10
-3
lines changed

bench/bench_bounded_q.ml

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ end = struct
2626
and not_empty = Condition.create ()
2727
and not_full = Condition.create () in
2828
{ mutex; queue; capacity; not_empty; not_full }
29+
|> Multicore_magic.copy_as_padded
2930

3031
let is_empty t =
3132
Mutex.lock t.mutex;
@@ -36,33 +37,39 @@ end = struct
3637
let is_full_unsafe t = t.capacity <= Queue.length t.queue
3738

3839
let push t x =
40+
let was_full = ref false in
3941
Mutex.lock t.mutex;
4042
match
4143
while is_full_unsafe t do
44+
was_full := true;
4245
Condition.wait t.not_full t.mutex
4346
done
4447
with
4548
| () ->
4649
Queue.push x t.queue;
4750
let n = Queue.length t.queue in
4851
Mutex.unlock t.mutex;
49-
if n = 1 then Condition.broadcast t.not_empty
52+
if n = 1 then Condition.signal t.not_empty;
53+
if !was_full && n < t.capacity then Condition.signal t.not_full
5054
| exception exn ->
5155
Mutex.unlock t.mutex;
5256
raise exn
5357

5458
let pop t =
59+
let was_empty = ref false in
5560
Mutex.lock t.mutex;
5661
match
5762
while Queue.length t.queue = 0 do
63+
was_empty := true;
5864
Condition.wait t.not_empty t.mutex
5965
done
6066
with
6167
| () ->
6268
let n = Queue.length t.queue in
6369
let elem = Queue.pop t.queue in
6470
Mutex.unlock t.mutex;
65-
if n = t.capacity then Condition.broadcast t.not_full;
71+
if n = t.capacity then Condition.signal t.not_full;
72+
if !was_empty && 1 < n then Condition.signal t.not_empty;
6673
elem
6774
| exception exn ->
6875
Mutex.unlock t.mutex;
@@ -73,7 +80,7 @@ end = struct
7380
let n = Queue.length t.queue in
7481
let elem_opt = Queue.take_opt t.queue in
7582
Mutex.unlock t.mutex;
76-
if n = t.capacity then Condition.broadcast t.not_full;
83+
if n = t.capacity then Condition.signal t.not_full;
7784
elem_opt
7885
end
7986

0 commit comments

Comments
 (0)