using ring buffer

main
Benjamin Kraft 2 years ago
parent a0893d11ba
commit 069f5f4bcf
  1. 30
      src/Queue.h
  2. 1
      src/Spectator.cpp

@ -7,6 +7,9 @@
#include <thread>
#include <QApplication>
#include <mutex>
#include <unordered_set>
#define MAX_QUEUE_SIZE 10
template<typename T>
class Queue {
@ -14,21 +17,31 @@ class Queue {
std::mutex mutex;
void run() {
while (!QApplication::closingDown()){
if (!container.empty())
if (!isEmpty())
update();
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
};
virtual void update() {}
std::vector<T *> container;
// First in
size_t tail = 0;
// First out
size_t head = 0;
T * container[MAX_QUEUE_SIZE];
protected:
bool isEmpty() const {
return tail == head;
}
size_t size() const {
return container.size();
}
T * pop(){
mutex.lock();
T * element = container.back();
container.pop_back();
T * element = container[head];
head = (head + 1) % MAX_QUEUE_SIZE;
mutex.unlock();
return element;
}
@ -38,7 +51,8 @@ public:
}
void push(T * element){
mutex.lock();
container.insert(container.begin(), element);
container[tail] = element;
tail = (tail + 1) % MAX_QUEUE_SIZE;
mutex.unlock();
}
};
@ -46,7 +60,7 @@ public:
template <typename EventType>
class EventQueue : protected Queue<EventType>{
std::vector<Listener<EventType> *> listeners;
std::unordered_set<Listener<EventType> *> listeners;
void update() override {
EventType * event = this->pop();
@ -60,10 +74,10 @@ public:
this->push(event);
}
void registerListener(Listener<EventType> * listener){
listeners.push_back(listener);
listeners.insert(listener);
}
void unregisterListener(Listener<EventType> * listener){
std::remove(listeners.begin(), listeners.end(), listener);
listeners.erase(listener);
}
};

@ -1,6 +1,7 @@
#include "Spectator.h"
#include <iostream>
#include "Game.h"
void Spectator::OnWallJumped(WallJumpEvent *event) {
std::cout << "Wall jump at " << event->time << std::endl;

Loading…
Cancel
Save