-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
mpsc: Added lightweight notification
- Loading branch information
1 parent
424ff3f
commit 123dbf8
Showing
3 changed files
with
117 additions
and
37 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
// | ||
// Created by shawn on 24-11-17. | ||
// | ||
|
||
#pragma once | ||
#include <atomic> | ||
#include <condition_variable> | ||
#include <mutex> | ||
|
||
namespace ulog { | ||
|
||
/** | ||
* @brief In conjunction with a lock-free queue, this notifier should be used when the queue is full or empty, as | ||
* retries can affect performance. | ||
*/ | ||
class LiteNotifier { | ||
public: | ||
template <typename Predicate> | ||
bool wait_for(std::chrono::milliseconds timeout, Predicate p) { | ||
if (p()) return true; | ||
|
||
std::unique_lock<std::mutex> lk(mtx_); | ||
|
||
auto ret = cv_.wait_for(lk, timeout, [&] { | ||
signal_needed = true; | ||
return p(); | ||
}); | ||
|
||
signal_needed = false; | ||
return ret; | ||
} | ||
|
||
void notify_when_blocking() { | ||
if (signal_needed.exchange(false)) { | ||
std::unique_lock<std::mutex> lk(mtx_); | ||
cv_.notify_all(); | ||
} | ||
} | ||
|
||
private: | ||
std::mutex mtx_; | ||
std::condition_variable cv_; | ||
std::atomic_bool signal_needed{false}; | ||
}; | ||
|
||
} // namespace ulog |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters