Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <functional>
- #include <chrono>
- #include <future>
- #include <queue>
- #include <thread>
- #include <iostream>
- using namespace std;
- struct TimerFunction {
- function<void()> func;
- chrono::system_clock::time_point time;
- TimerFunction() {}
- TimerFunction(function<void()> & func, chrono::system_clock::time_point & time) : func(func), time(time) {}
- bool operator < (const TimerFunction & rhs) const {
- return this->time > rhs.time;
- }
- };
- class TaskScheduler {
- public:
- TaskScheduler(int num_threads){
- for(int i = 0; i < num_threads; ++i) {
- worker_threads_.emplace_back(make_unique<thread>(&TaskScheduler::FunctionRunner, this));
- }
- cout << "creating scheduler" << endl;
- }
- ~TaskScheduler() {
- is_running_ = false;
- for (const auto& worker : worker_threads_) {
- worker->join();
- }
- cout << "deleting scheduler" << endl;
- }
- void Schedule(function<void()> && func, chrono::system_clock::time_point && time) {
- if (!is_running_) {
- return;
- }
- unique_lock<mutex> lock(mutex_);
- queue_.push(TimerFunction(func, time));
- lock.unlock();
- cv_.notify_one();
- }
- private:
- void FunctionRunner() {
- while (is_running_) {
- auto now = chrono::system_clock::now();
- unique_lock<mutex> lock(mutex_);
- cv_.wait_for(lock, 5ms, [this]() {return !queue_.empty();});
- if (queue_.empty()) {
- continue;
- }
- auto timer_func = queue_.top();
- if (timer_func.time > now) {
- continue;
- }
- queue_.pop();
- lock.unlock();
- timer_func.func();
- }
- }
- condition_variable cv_;
- mutex mutex_;
- priority_queue<TimerFunction> queue_;
- bool is_running_ = true;
- vector<unique_ptr<thread>> worker_threads_;
- };
- int main(int argc, char** argv) {
- TaskScheduler scheduler(5);
- scheduler.Schedule([]() {cout << "50ms" << endl;}, chrono::system_clock::now() + chrono::milliseconds(50));
- scheduler.Schedule([]() {cout << "10ms" << endl;}, chrono::system_clock::now() + chrono::milliseconds(10));
- scheduler.Schedule([]() {cout << "30ms" << endl;}, chrono::system_clock::now() + chrono::milliseconds(30));
- this_thread::sleep_for(chrono::milliseconds(100));
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement