tasks.h

main 91 lines · 2.5 KB Raw
Alex Alex Commit Server upload 18/10/2026 23:38
1/**
2 * The Forgotten Server - a free and open-source MMORPG server emulator
3 * Copyright (C) 2019 Mark Samman <mark.samman@gmail.com>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20#ifndef FS_TASKS_H_A66AC384766041E59DCA059DAB6E1976
21#define FS_TASKS_H_A66AC384766041E59DCA059DAB6E1976
22
23#include <condition_variable>
24#include "thread_holder_base.h"
25#include "enums.h"
26
27const int DISPATCHER_TASK_EXPIRATION = 2000;
28const auto SYSTEM_TIME_ZERO = std::chrono::system_clock::time_point(std::chrono::milliseconds(0));
29
30class Task
31{
32 public:
33 // DO NOT allocate this class on the stack
34 explicit Task(std::function<void (void)>&& f) : func(std::move(f)) {}
35 Task(uint32_t ms, std::function<void (void)>&& f) :
36 expiration(std::chrono::system_clock::now() + std::chrono::milliseconds(ms)), func(std::move(f)) {}
37
38 virtual ~Task() = default;
39 void operator()() {
40 func();
41 }
42
43 void setDontExpire() {
44 expiration = SYSTEM_TIME_ZERO;
45 }
46
47 bool hasExpired() const {
48 if (expiration == SYSTEM_TIME_ZERO) {
49 return false;
50 }
51 return expiration < std::chrono::system_clock::now();
52 }
53
54 protected:
55 std::chrono::system_clock::time_point expiration = SYSTEM_TIME_ZERO;
56
57 private:
58 // Expiration has another meaning for scheduler tasks,
59 // then it is the time the task should be added to the
60 // dispatcher
61 std::function<void (void)> func;
62};
63
64Task* createTask(std::function<void (void)> f);
65Task* createTask(uint32_t expiration, std::function<void (void)> f);
66
67class Dispatcher : public ThreadHolder<Dispatcher> {
68 public:
69 void addTask(Task* task, bool push_front = false);
70
71 void shutdown();
72
73 uint64_t getDispatcherCycle() const {
74 return dispatcherCycle;
75 }
76
77 void threadMain();
78
79 private:
80 std::thread thread;
81 std::mutex taskLock;
82 std::condition_variable taskSignal;
83
84 std::list<Task*> taskList;
85 uint64_t dispatcherCycle = 0;
86};
87
88extern Dispatcher g_dispatcher;
89
90#endif
91
Top