aboutsummaryrefslogtreecommitdiffstats
path: root/source/core/core_job.cpp
blob: 4b1b44c630c8a5c8a90d924dd38819554f62fd1f (plain) (blame)
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
internal void job_queue_init(Arena *arena, JobQueue *queue, u32 capacity_pow2)
{
	Assert(is_pow(capacity_pow2));
	MemSetZero(queue, sizeof(*queue));
	queue->capacity = capacity_pow2;
	queue->mask     = capacity_pow2 - 1;
	queue->items    = PushArray(arena, u32, capacity_pow2);
}

internal b32 job_queue_push_back(JobQueue *queue, u32 item)
{
	spin_lock(&queue->lock);
	b32 ok = queue->count < queue->capacity;
	if(ok) {
		queue->items[(queue->head + queue->count) & queue->mask] = item;
		++queue->count;
	}
	spin_unlock(&queue->lock);

	if(ok) {
		signal_notify(&queue->signal);
	}
	return ok;
}

internal b32 job_queue_push_front(JobQueue *queue, u32 item)
{
	spin_lock(&queue->lock);
	b32 ok = queue->count < queue->capacity;
	if(ok) {
		queue->head               = (queue->head - 1) & queue->mask;
		queue->items[queue->head] = item;
		++queue->count;
	}
	spin_unlock(&queue->lock);

	if(ok) {
		signal_notify(&queue->signal);
	}
	return ok;
}

internal b32 job_queue_pop(JobQueue *queue, u32 *out)
{
	for(;;) {
		// NOTE: snapshot before checking, so a push between the check and the wait wakes us
		u32 snapshot = signal_snapshot(&queue->signal);

		if(AtomicLoad(&queue->quit)) {
			return false;
		}

		spin_lock(&queue->lock);
		b32 got = queue->count > 0;
		if(got) {
			*out        = queue->items[queue->head];
			queue->head = (queue->head + 1) & queue->mask;
			--queue->count;
		}
		spin_unlock(&queue->lock);

		if(got) {
			return true;
		}

		signal_wait(&queue->signal, snapshot, -1);
	}
}

internal u32 job_queue_count(JobQueue *queue)
{
	return AtomicLoadRelaxed(&queue->count);
}

internal void job_queue_quit(JobQueue *queue)
{
	AtomicStore(&queue->quit, 1u);
	signal_notify(&queue->signal);
}