]> git.lizzy.rs Git - dragonfireclient.git/blob - src/script/cpp_api/s_async.h
Fix CSM crash (#5779)
[dragonfireclient.git] / src / script / cpp_api / s_async.h
1 /*
2 Minetest
3 Copyright (C) 2013 sapier, <sapier AT gmx DOT net>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser 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 CPP_API_ASYNC_EVENTS_HEADER
21 #define CPP_API_ASYNC_EVENTS_HEADER
22
23 #include <vector>
24 #include <deque>
25 #include <map>
26
27 #include "threading/thread.h"
28 #include "threading/mutex.h"
29 #include "threading/semaphore.h"
30 #include "debug.h"
31 #include "lua.h"
32 #include "cpp_api/s_base.h"
33
34 // Forward declarations
35 class AsyncEngine;
36
37
38 // Declarations
39
40 // Data required to queue a job
41 struct LuaJobInfo
42 {
43         LuaJobInfo() :
44                 serializedFunction(""),
45                 serializedParams(""),
46                 serializedResult(""),
47                 id(0),
48                 valid(false)
49         {}
50
51         // Function to be called in async environment
52         std::string serializedFunction;
53         // Parameter to be passed to function
54         std::string serializedParams;
55         // Result of function call
56         std::string serializedResult;
57         // JobID used to identify a job and match it to callback
58         unsigned int id;
59
60         bool valid;
61 };
62
63 // Asynchronous working environment
64 class AsyncWorkerThread : public Thread, public ScriptApiBase {
65 public:
66         AsyncWorkerThread(AsyncEngine* jobDispatcher, const std::string &name);
67         virtual ~AsyncWorkerThread();
68
69         void *run();
70
71 private:
72         AsyncEngine *jobDispatcher;
73 };
74
75 // Asynchornous thread and job management
76 class AsyncEngine {
77         friend class AsyncWorkerThread;
78         typedef void (*StateInitializer)(lua_State *L, int top);
79 public:
80         AsyncEngine();
81         ~AsyncEngine();
82
83         /**
84          * Register function to be called on new states
85          * @param func C function to be called
86          */
87         void registerStateInitializer(StateInitializer func);
88
89         /**
90          * Create async engine tasks and lock function registration
91          * @param numEngines Number of async threads to be started
92          */
93         void initialize(unsigned int numEngines);
94
95         /**
96          * Queue an async job
97          * @param func Serialized lua function
98          * @param params Serialized parameters
99          * @return jobid The job is queued
100          */
101         unsigned int queueAsyncJob(const std::string &func, const std::string &params);
102
103         /**
104          * Engine step to process finished jobs
105          *   the engine step is one way to pass events back, PushFinishedJobs another
106          * @param L The Lua stack
107          */
108         void step(lua_State *L);
109
110         /**
111          * Push a list of finished jobs onto the stack
112          * @param L The Lua stack
113          */
114         void pushFinishedJobs(lua_State *L);
115
116 protected:
117         /**
118          * Get a Job from queue to be processed
119          *  this function blocks until a job is ready
120          * @return a job to be processed
121          */
122         LuaJobInfo getJob();
123
124         /**
125          * Put a Job result back to result queue
126          * @param result result of completed job
127          */
128         void putJobResult(const LuaJobInfo &result);
129
130         /**
131          * Initialize environment with current registred functions
132          *  this function adds all functions registred by registerFunction to the
133          *  passed lua stack
134          * @param L Lua stack to initialize
135          * @param top Stack position
136          */
137         void prepareEnvironment(lua_State* L, int top);
138
139 private:
140         // Variable locking the engine against further modification
141         bool initDone;
142
143         // Internal store for registred state initializers
144         std::vector<StateInitializer> stateInitializers;
145
146         // Internal counter to create job IDs
147         unsigned int jobIdCounter;
148
149         // Mutex to protect job queue
150         Mutex jobQueueMutex;
151
152         // Job queue
153         std::deque<LuaJobInfo> jobQueue;
154
155         // Mutex to protect result queue
156         Mutex resultQueueMutex;
157         // Result queue
158         std::deque<LuaJobInfo> resultQueue;
159
160         // List of current worker threads
161         std::vector<AsyncWorkerThread*> workerThreads;
162
163         // Counter semaphore for job dispatching
164         Semaphore jobQueueCounter;
165 };
166
167 #endif // CPP_API_ASYNC_EVENTS_HEADER