File: Executor.h

package info (click to toggle)
freespace2 24.2.0%2Brepack-1
  • links: PTS, VCS
  • area: non-free
  • in suites: forky, sid
  • size: 43,716 kB
  • sloc: cpp: 595,001; ansic: 21,741; python: 1,174; sh: 457; makefile: 248; xml: 181
file content (54 lines) | stat: -rw-r--r-- 1,477 bytes parent folder | download | duplicates (2)
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
#pragma once

#include "globalincs/pstypes.h"

#include <mutex>

namespace executor {

/**
 * @brief A class that collects work that should be executed repeatedly.
 *
 * The intention behind this is that the engine code creates executor objects and then calls process() on them at
 * specific points of the engine code. External code can then post() work items to be executed when that point of the
 * code is reached without introducing a hard dependency between the two code modules.
 *
 * Work items have the option of specifying that they should be rescheduled for the next execution round.
 *
 * @note This class is thread safe and work items can be posted to the executor from different threads without risking
 * data corruption.
 */
class Executor {
  public:
	enum class CallbackResult {
		Done,       //! The work item is finished
		Reschedule, //! The work item should be executed again in the next round
	};

	using Callback = std::function<CallbackResult()>;

	/**
	 * @brief Adds a work item to this executor
	 *
	 * This work item will be executed every time process() is called until it returns CallbackResult::Done.
	 *
	 * @param cb The work item
	 */
	void post(Callback cb);

	/**
	 * @brief Executes one round of work items
	 */
	void process();

  private:
	std::mutex m_mainMutex;
	SCP_vector<Callback> m_workItems;

	std::mutex m_pendingWorkItemsMutex;
	SCP_vector<Callback> m_pendingWorkItems;
};

Executor* currentExecutor();

} // namespace executor