-
Notifications
You must be signed in to change notification settings - Fork 0
/
jobsys.h
76 lines (66 loc) · 1.71 KB
/
jobsys.h
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
#pragma once
#include "precomp.h"
#include <functional>
#include <future>
#include <functional>
namespace JobSystem {
// Fixed size very simple thread safe ring buffer -
// Credit to: https://wickedengine.net/2018/11/24/simple-job-system-using-standard-c/
template <typename T, size_t capacity>
class ThreadSafeRingBuffer
{
public:
// Push an item to the end if there is free space
// Returns true if successful
// Returns false if there is not enough space
inline bool push_back(const T& item)
{
bool result = false;
lock.lock();
const size_t next = (head + 1) % capacity;
if (next != tail)
{
data[head] = item;
head = next;
result = true;
}
lock.unlock();
return result;
}
// Get an item if there are any
// Returns true if successful
// Returns false if there are no items
inline bool pop_front(T& item)
{
bool result = false;
lock.lock();
if (tail != head)
{
item = data[tail];
tail = (tail + 1) % capacity;
result = true;
}
lock.unlock();
return result;
}
private:
T data[capacity];
size_t head = 0;
size_t tail = 0;
std::mutex lock; // this just works better than a spinlock here (on windows)
};
// A Dispatched job will receive this as function argument:
struct JobDispatchArgs
{
uint32_t jobIndex;
uint32_t groupIndex;
};
// Create the internal resources such as worker threads, etc. Call it once when initializing the application.
void Initialize();
// Add a job to execute asynchronously. Any idle thread will execute this job.
void Execute(const std::function<void()>& job);
// Check if any threads are working currently or not
bool IsBusy();
// Wait until all threads become idle
void Wait();
}