Problems with add
:
- the while(true) is useless
- you want to
notify_one
, notnotify_all
because you've only added one thing, and so only one thread waiting to remove can remove it. - you should overload for two version which take
const T&
andT&&
(the latter wouldstd::move
). This would be optimal in all cases. (analogous topush_back
in standard containers) - You may also want to add an
emplace
to complement theadd()
versions so you can constructT
in-place at the top of the Buffer. - you can use
lock_guard
instead ofunique_lock
and scope it with{}
s. I'd just say always prefer the lighter weight construct when a heavier weight one isn't strictly needed.
problems with remove
:
- the
while (true)
is useless - the cond var lambda can be
return !buffer.empty();
- the back variable can be
std::move
d - what happens if you destruct an empty
Buffer
while a thread is waiting onremove
? That case isn't handled at all, and it's a problem - there's no reason to
notify_all
inremove
. Who is it notifying and why?
problems with size
:
- use a
lock_guard
unlessunique_lock
is needed - just do:
std::lock_guard<std::mutex> lock{mu}; return buffer.size();