2025-03-12 14:18:44 +00:00
|
|
|
/*
|
|
|
|
* AsyncRunner.h, part of VCMI engine
|
|
|
|
*
|
|
|
|
* Authors: listed in file AUTHORS in main folder
|
|
|
|
*
|
|
|
|
* License: GNU General Public License v2.0 or later
|
|
|
|
* Full text of license available in license.txt file, in main folder
|
|
|
|
*
|
|
|
|
*/
|
|
|
|
#pragma once
|
|
|
|
|
|
|
|
#include <tbb/task_arena.h>
|
2025-03-12 15:57:06 +00:00
|
|
|
#include <tbb/task_group.h>
|
2025-03-12 14:18:44 +00:00
|
|
|
|
|
|
|
VCMI_LIB_NAMESPACE_BEGIN
|
|
|
|
|
2025-03-12 15:57:06 +00:00
|
|
|
/// Helper class for running asynchronous tasks using TBB thread pool
|
2025-03-12 14:18:44 +00:00
|
|
|
class AsyncRunner : boost::noncopyable
|
|
|
|
{
|
|
|
|
tbb::task_arena arena;
|
|
|
|
tbb::task_group taskGroup;
|
|
|
|
|
|
|
|
public:
|
2025-03-12 15:57:06 +00:00
|
|
|
/// Runs the provided functor asynchronously on a thread from the TBB worker pool.
|
|
|
|
template<typename Functor>
|
2025-03-12 14:18:44 +00:00
|
|
|
void run(Functor && f)
|
|
|
|
{
|
|
|
|
arena.enqueue(taskGroup.defer(std::forward<Functor>(f)));
|
|
|
|
}
|
|
|
|
|
2025-03-12 15:57:06 +00:00
|
|
|
/// Waits for all previously enqueued task.
|
|
|
|
/// Re-entrable - waiting for tasks does not prevent submitting new tasks
|
2025-03-12 14:18:44 +00:00
|
|
|
void wait()
|
|
|
|
{
|
|
|
|
taskGroup.wait();
|
|
|
|
}
|
|
|
|
|
|
|
|
~AsyncRunner()
|
|
|
|
{
|
|
|
|
wait();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
VCMI_LIB_NAMESPACE_END
|