55 lines
1.3 KiB
C
55 lines
1.3 KiB
C
|
#pragma once
|
||
|
|
||
|
#include <mutex>
|
||
|
#include <memory>
|
||
|
#include <vector>
|
||
|
#include <string>
|
||
|
#include <thread>
|
||
|
#include <condition_variable>
|
||
|
|
||
|
namespace tc {
|
||
|
namespace event {
|
||
|
class EventExecutor;
|
||
|
class EventEntry {
|
||
|
friend class EventExecutor;
|
||
|
public:
|
||
|
virtual void event_execute(const std::chrono::system_clock::time_point& /* scheduled timestamp */) = 0;
|
||
|
|
||
|
private:
|
||
|
void* _event_ptr = nullptr;
|
||
|
};
|
||
|
|
||
|
class EventExecutor {
|
||
|
public:
|
||
|
explicit EventExecutor(const std::string& /* thread prefix */);
|
||
|
virtual ~EventExecutor();
|
||
|
|
||
|
bool initialize(int /* num threads */);
|
||
|
bool schedule(const std::shared_ptr<EventEntry>& /* entry */);
|
||
|
bool cancel(const std::shared_ptr<EventEntry>& /* entry */); /* Note: Will not cancel already running executes */
|
||
|
void shutdown();
|
||
|
private:
|
||
|
struct LinkedEntry {
|
||
|
LinkedEntry* previous;
|
||
|
LinkedEntry* next;
|
||
|
|
||
|
std::chrono::system_clock::time_point scheduled;
|
||
|
std::weak_ptr<EventEntry> entry;
|
||
|
};
|
||
|
static void _executor(EventExecutor*);
|
||
|
void _shutdown(std::unique_lock<std::mutex>&);
|
||
|
void _reset_events(std::unique_lock<std::mutex>&);
|
||
|
|
||
|
bool should_shutdown = true;
|
||
|
|
||
|
std::vector<std::thread> threads;
|
||
|
std::mutex lock;
|
||
|
std::condition_variable condition;
|
||
|
|
||
|
LinkedEntry* head = nullptr;
|
||
|
LinkedEntry* tail = nullptr;
|
||
|
|
||
|
std::string thread_prefix;
|
||
|
};
|
||
|
}
|
||
|
}
|