Blender V5.3
gpu_worker.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2025 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
8
9#include "GPU_worker.hh"
10
11namespace blender::gpu {
12
13GPUWorker::GPUWorker(uint32_t threads_count, ContextType context_type, WorkCallback callback)
14 : callback_(callback)
15{
16 work_queue_ = BLI_thread_queue_init();
17
18 for (int i : IndexRange(threads_count)) {
19 UNUSED_VARS(i);
20 std::shared_ptr<GPUSecondaryContext> thread_context =
21 context_type == ContextType::PerThread ? std::make_shared<GPUSecondaryContext>() : nullptr;
22 threads_.append(
23 std::make_unique<std::thread>([this, thread_context]() { this->run(thread_context); }));
24 }
25}
26
28{
29 /* Any work left should have been cancelled at this point. */
31 /* Signal background threads to stop waiting for new tasks if none are left. */
32 BLI_thread_queue_nowait(work_queue_);
33 /* But we still wait, in case the above assert fails. */
35 for (std::unique_ptr<std::thread> &thread : threads_) {
36 thread->join();
37 }
38 BLI_thread_queue_free(work_queue_);
39}
40
42{
43 return BLI_thread_queue_push(work_queue_, work, priority);
44}
45
47{
48 return BLI_thread_queue_cancel_work(work_queue_, id);
49}
50
52{
53 return BLI_thread_queue_is_empty(work_queue_);
54}
55
56void GPUWorker::run(std::shared_ptr<GPUSecondaryContext> context)
57{
58 if (context) {
59 context->activate();
60 }
61
62 /* Loop until the queue is cancelled. */
63 while (void *work = BLI_thread_queue_pop(work_queue_)) {
64 callback_(work);
65 }
66}
67
68} // namespace blender::gpu
#define UNUSED_VARS(...)
constexpr IndexRange()=default
GPUWorker(uint32_t threads_count, ContextType context_type, WorkCallback callback)
Definition gpu_worker.cc:13
WorkID push_work(void *work, ThreadQueueWorkPriority priority)
Definition gpu_worker.cc:41
bool cancel_work(WorkID id)
Definition gpu_worker.cc:46
bool join()
Definition thread.cpp:48
void(*)(void *) WorkCallback
Definition GPU_worker.hh:24
uint64_t WorkID
Definition GPU_worker.hh:25
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
void BLI_thread_queue_nowait(ThreadQueue *queue)
Definition threads.cc:856
ThreadQueueWorkPriority
bool BLI_thread_queue_cancel_work(ThreadQueue *queue, uint64_t work_id)
Definition threads.cc:687
void BLI_thread_queue_wait_finish(ThreadQueue *queue)
Definition threads.cc:867
bool BLI_thread_queue_is_empty(ThreadQueue *queue)
Definition threads.cc:844
unsigned int uint32_t
Definition BKE_text.h:81
void BLI_thread_queue_free(ThreadQueue *queue)
Definition threads.cc:638
ThreadQueue * BLI_thread_queue_init()
Definition threads.cc:627
void * BLI_thread_queue_pop(ThreadQueue *queue)
Definition threads.cc:717
uint64_t BLI_thread_queue_push(ThreadQueue *queue, void *work, ThreadQueueWorkPriority priority)
Definition threads.cc:648