Skip to content

Instantly share code, notes, and snippets.

@eao197
Created February 9, 2024 09:58
Show Gist options
  • Save eao197/619518962e1c0ce608b295ff162cfe89 to your computer and use it in GitHub Desktop.
Save eao197/619518962e1c0ce608b295ff162cfe89 to your computer and use it in GitHub Desktop.
Вольная вариация на тему std::latch, но для ситуации, когда значение счетчика заранее неизвестно.
class meeting_room_t {
std::mutex lock_;
std::condition_variable wakeup_cv_;
unsigned attenders_{};
public:
meeting_room_t() = default;
void enter() {
std::lock_guard<std::mutex> lock{lock_};
++attenders_;
}
void leave() {
std::lock_guard<std::mutex> lock{lock_};
--attenders_;
if(!attenders_)
wakeup_cv_.notify_all();
}
void wait_for_emptiness() {
std::unique_lock<std::mutex> lock{lock_};
if(attenders_)
{
wakeup_cv_.wait(lock, [this]{ return 0u == attenders_; });
}
}
};
class auto_enter_leave_t {
meeting_room_t & room_;
public:
auto_enter_leave_t(meeting_room_t & room) : room_{room} {
room_.enter();
}
~auto_enter_leave_t() {
room_.leave();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment