Skip to content

Commit

Permalink
thread_safe_queue: sync changes from the version in libxmotion
Browse files Browse the repository at this point in the history
  • Loading branch information
rxdu committed Nov 16, 2024
1 parent f0c3da0 commit e582bd1
Showing 1 changed file with 59 additions and 37 deletions.
96 changes: 59 additions & 37 deletions src/imview/include/imview/component/event/thread_safe_queue.hpp
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
/*
* @file thread_safe_queue.hpp
* @date 10/10/24
* @brief
*
* @copyright Copyright (c) 2024 Ruixiang Du (rdu)
*/
* @file thread_safe_queue.hpp
* @date 10/10/24
* @brief
*
* @copyright Copyright (c) 2024 Ruixiang Du (rdu)
*/
#ifndef QUICKVIZ_THREAD_SAFE_QUEUE_HPP
#define QUICKVIZ_THREAD_SAFE_QUEUE_HPP

Expand All @@ -16,37 +16,59 @@
namespace quickviz {
template <typename T>
class ThreadSafeQueue {
public:
// Push data into the queue
void Push(const T& data) {
std::lock_guard<std::mutex> lock(mutex_);
queue_.push(data);
condition_.notify_one(); // Notify one waiting thread
}

// Pop data from the queue (blocking)
T Pop() {
std::unique_lock<std::mutex> lock(mutex_);
condition_.wait(lock, [this] { return !queue_.empty(); });
T data = queue_.front();
queue_.pop();
return data;
}

// Try to pop data from the queue (non-blocking)
bool TryPop(T& data) {
std::lock_guard<std::mutex> lock(mutex_);
if (queue_.empty()) return false;
data = queue_.front();
queue_.pop();
return true;
}

private:
std::queue<T> queue_;
std::mutex mutex_;
std::condition_variable condition_;
public:
ThreadSafeQueue() = default;
~ThreadSafeQueue() = default;

// do not allow copy
ThreadSafeQueue(const ThreadSafeQueue&) = delete;
ThreadSafeQueue& operator=(const ThreadSafeQueue&) = delete;

// allow move
ThreadSafeQueue(ThreadSafeQueue&&) noexcept {
std::lock_guard<std::mutex> lock(mutex_);
queue_ = std::move(queue_);
}

ThreadSafeQueue& operator=(ThreadSafeQueue&& other) noexcept {
if (this != &other) {
std::lock_guard<std::mutex> lock(mutex_);
std::lock_guard<std::mutex> lock_other(other.mutex_);
queue_ = std::move(other.queue_);
}
return *this;
}

// push data into the queue
void Push(const T& data) {
std::lock_guard<std::mutex> lock(mutex_);
queue_.push(data);
condition_.notify_one(); // Notify one waiting thread
}

// pop data from the queue (blocking)
T Pop() {
std::unique_lock<std::mutex> lock(mutex_);
condition_.wait(lock, [this] { return !queue_.empty(); });
T data = queue_.front();
queue_.pop();
return data;
}

// try to pop data from the queue (non-blocking)
bool TryPop(T& data) {
std::lock_guard<std::mutex> lock(mutex_);
if (queue_.empty()) return false;
data = queue_.front();
queue_.pop();
return true;
}

private:
std::queue<T> queue_;
std::mutex mutex_;
std::condition_variable condition_;
};
} // namespace quickviz
} // namespace xmotion

#endif // QUICKVIZ_THREAD_SAFE_QUEUE_HPP

0 comments on commit e582bd1

Please sign in to comment.