forked from otland/forgottenserver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabasetasks.cpp
88 lines (76 loc) · 1.84 KB
/
databasetasks.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// Copyright 2022 The Forgotten Server Authors. All rights reserved.
// Use of this source code is governed by the GPL-2.0 License that can be found in the LICENSE file.
#include "otpch.h"
#include "databasetasks.h"
#include "tasks.h"
extern Dispatcher g_dispatcher;
void DatabaseTasks::start()
{
db.connect();
ThreadHolder::start();
}
void DatabaseTasks::threadMain()
{
std::unique_lock<std::mutex> taskLockUnique(taskLock, std::defer_lock);
while (getState() != THREAD_STATE_TERMINATED) {
taskLockUnique.lock();
if (tasks.empty()) {
taskSignal.wait(taskLockUnique);
}
if (!tasks.empty()) {
DatabaseTask task = std::move(tasks.front());
tasks.pop_front();
taskLockUnique.unlock();
runTask(task);
} else {
taskLockUnique.unlock();
}
}
}
void DatabaseTasks::addTask(std::string query, std::function<void(DBResult_ptr, bool)> callback/* = nullptr*/, bool store/* = false*/)
{
bool signal = false;
taskLock.lock();
if (getState() == THREAD_STATE_RUNNING) {
signal = tasks.empty();
tasks.emplace_back(std::move(query), std::move(callback), store);
}
taskLock.unlock();
if (signal) {
taskSignal.notify_one();
}
}
void DatabaseTasks::runTask(const DatabaseTask& task)
{
bool success;
DBResult_ptr result;
if (task.store) {
result = db.storeQuery(task.query);
success = true;
} else {
result = nullptr;
success = db.executeQuery(task.query);
}
if (task.callback) {
g_dispatcher.addTask(createTask(std::bind(task.callback, result, success)));
}
}
void DatabaseTasks::flush()
{
std::unique_lock<std::mutex> guard{ taskLock };
while (!tasks.empty()) {
auto task = std::move(tasks.front());
tasks.pop_front();
guard.unlock();
runTask(task);
guard.lock();
}
}
void DatabaseTasks::shutdown()
{
taskLock.lock();
setState(THREAD_STATE_TERMINATED);
taskLock.unlock();
flush();
taskSignal.notify_one();
}