Skip to content

Commit

Permalink
make thread safe fifo take less cpu
Browse files Browse the repository at this point in the history
  • Loading branch information
marenz2569 committed Jul 2, 2024
1 parent ee0b1e0 commit dd72bd3
Showing 1 changed file with 16 additions and 0 deletions.
16 changes: 16 additions & 0 deletions include/thread_safe_fifo.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

#pragma once

#include <condition_variable>
#include <deque>
#include <mutex>
#include <optional>
Expand Down Expand Up @@ -37,7 +38,18 @@ template <typename T> class ThreadSafeFifo {
if (!queue_.empty()) {
result = std::forward<T>(queue_.front());
queue_.pop_front();

return result;
}
cv_.wait_for(lk, 10ms, [&] {
if (!queue_.empty()) {
auto result = std::forward<T>(queue_.front());
queue_.pop_front();

return true;
}
return false;
});
}

return result;
Expand All @@ -51,12 +63,16 @@ template <typename T> class ThreadSafeFifo {
auto push_back(T&& element) -> void {
std::lock_guard<std::mutex> lk(mutex_);
queue_.push_back(std::forward<T>(element));
cv_.notify_one();
};

private:
/// the mutex that is used to access the queue.
std::mutex mutex_;

/// the condition variable that is set when an item was inserted
std::condition_variable cv_;

/// the wrapped queue
std::deque<T> queue_;
};

0 comments on commit dd72bd3

Please sign in to comment.