2025-04-07 15:26:25 +02:00
|
|
|
/* SPDX-FileCopyrightText: 2025 Blender Authors
|
|
|
|
|
*
|
|
|
|
|
* SPDX-License-Identifier: GPL-2.0-or-later */
|
|
|
|
|
|
|
|
|
|
#include "GPU_worker.hh"
|
|
|
|
|
|
|
|
|
|
namespace blender::gpu {
|
|
|
|
|
|
2025-05-08 18:16:47 +02:00
|
|
|
GPUWorker::GPUWorker(uint32_t threads_count,
|
|
|
|
|
ContextType context_type,
|
2025-06-10 17:24:18 +02:00
|
|
|
std::mutex &mutex,
|
|
|
|
|
std::function<void *()> pop_work,
|
|
|
|
|
std::function<void(void *)> do_work)
|
|
|
|
|
: mutex_(mutex)
|
2025-04-07 15:26:25 +02:00
|
|
|
{
|
|
|
|
|
for (int i : IndexRange(threads_count)) {
|
|
|
|
|
UNUSED_VARS(i);
|
|
|
|
|
std::shared_ptr<GPUSecondaryContext> thread_context =
|
2025-05-08 18:16:47 +02:00
|
|
|
context_type == ContextType::PerThread ? std::make_shared<GPUSecondaryContext>() : nullptr;
|
2025-06-10 17:24:18 +02:00
|
|
|
threads_.append(
|
|
|
|
|
std::make_unique<std::thread>([=]() { this->run(thread_context, pop_work, do_work); }));
|
2025-04-07 15:26:25 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
GPUWorker::~GPUWorker()
|
|
|
|
|
{
|
2025-06-10 17:24:18 +02:00
|
|
|
{
|
|
|
|
|
std::unique_lock<std::mutex> lock(mutex_);
|
|
|
|
|
terminate_ = true;
|
|
|
|
|
}
|
2025-04-07 15:26:25 +02:00
|
|
|
condition_var_.notify_all();
|
|
|
|
|
for (std::unique_ptr<std::thread> &thread : threads_) {
|
|
|
|
|
thread->join();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-06-10 17:24:18 +02:00
|
|
|
void GPUWorker::run(std::shared_ptr<GPUSecondaryContext> context,
|
|
|
|
|
std::function<void *()> pop_work,
|
|
|
|
|
std::function<void(void *)> do_work)
|
2025-04-07 15:26:25 +02:00
|
|
|
{
|
2025-05-08 18:16:47 +02:00
|
|
|
if (context) {
|
|
|
|
|
context->activate();
|
|
|
|
|
}
|
2025-04-07 15:26:25 +02:00
|
|
|
|
2025-06-10 17:24:18 +02:00
|
|
|
std::unique_lock<std::mutex> lock(mutex_);
|
|
|
|
|
|
2025-04-07 15:26:25 +02:00
|
|
|
/* Loop until we get the terminate signal. */
|
|
|
|
|
while (!terminate_) {
|
2025-06-10 17:24:18 +02:00
|
|
|
void *work = pop_work();
|
|
|
|
|
if (!work) {
|
2025-04-07 15:26:25 +02:00
|
|
|
condition_var_.wait(lock);
|
2025-06-10 17:24:18 +02:00
|
|
|
if (terminate_) {
|
|
|
|
|
break;
|
|
|
|
|
}
|
2025-04-07 15:26:25 +02:00
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
2025-06-10 17:24:18 +02:00
|
|
|
lock.unlock();
|
|
|
|
|
do_work(work);
|
|
|
|
|
lock.lock();
|
2025-04-07 15:26:25 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
} // namespace blender::gpu
|