tasks.cpp

main 107 lines · 2.4 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#include "otpch.h"
21
22#include "tasks.h"
23#include "game.h"
24
25extern Game g_game;
26
27Task* createTask(std::function<void (void)> f)
28{
29 return new Task(std::move(f));
30}
31
32Task* createTask(uint32_t expiration, std::function<void (void)> f)
33{
34 return new Task(expiration, std::move(f));
35}
36
37void Dispatcher::threadMain()
38{
39 // NOTE: second argument defer_lock is to prevent from immediate locking
40 std::unique_lock<std::mutex> taskLockUnique(taskLock, std::defer_lock);
41
42 while (getState() != THREAD_STATE_TERMINATED) {
43 // check if there are tasks waiting
44 taskLockUnique.lock();
45
46 if (taskList.empty()) {
47 //if the list is empty wait for signal
48 taskSignal.wait(taskLockUnique);
49 }
50
51 if (!taskList.empty()) {
52 // take the first task
53 Task* task = taskList.front();
54 taskList.pop_front();
55 taskLockUnique.unlock();
56
57 if (!task->hasExpired()) {
58 ++dispatcherCycle;
59 // execute it
60 (*task)();
61 }
62 delete task;
63 } else {
64 taskLockUnique.unlock();
65 }
66 }
67}
68
69void Dispatcher::addTask(Task* task, bool push_front /*= false*/)
70{
71 bool do_signal = false;
72
73 taskLock.lock();
74
75 if (getState() == THREAD_STATE_RUNNING) {
76 do_signal = taskList.empty();
77
78 if (push_front) {
79 taskList.push_front(task);
80 } else {
81 taskList.push_back(task);
82 }
83 } else {
84 delete task;
85 }
86
87 taskLock.unlock();
88
89 // send a signal if the list was empty
90 if (do_signal) {
91 taskSignal.notify_one();
92 }
93}
94
95void Dispatcher::shutdown()
96{
97 Task* task = createTask([this]() {
98 setState(THREAD_STATE_TERMINATED);
99 taskSignal.notify_one();
100 });
101
102 std::lock_guard<std::mutex> lockClass(taskLock);
103 taskList.push_back(task);
104
105 taskSignal.notify_one();
106}
107
Top