2022-03-16 18:41:41 +00:00
|
|
|
#include "threadPoolCallbackRunner.h"
|
|
|
|
|
2022-04-27 15:05:45 +00:00
|
|
|
#include <Common/scope_guard_safe.h>
|
2022-03-16 18:41:41 +00:00
|
|
|
#include <Common/CurrentThread.h>
|
2022-09-07 15:44:29 +00:00
|
|
|
#include <Common/setThreadName.h>
|
|
|
|
#include <IO/AsynchronousReader.h>
|
|
|
|
#include <future>
|
|
|
|
|
2022-03-16 18:41:41 +00:00
|
|
|
|
|
|
|
namespace DB
|
|
|
|
{
|
|
|
|
|
2022-09-07 15:44:29 +00:00
|
|
|
template <typename Result> ThreadPoolCallbackRunner<Result> threadPoolCallbackRunner(ThreadPool & pool, const std::string & thread_name)
|
2022-03-16 18:41:41 +00:00
|
|
|
{
|
2022-09-07 15:44:29 +00:00
|
|
|
return [pool = &pool, thread_group = CurrentThread::getGroup(), thread_name](std::function<Result()> && callback, size_t priority) mutable -> std::future<Result>
|
2022-03-16 18:41:41 +00:00
|
|
|
{
|
2022-09-07 15:44:29 +00:00
|
|
|
auto task = std::make_shared<std::packaged_task<Result()>>([thread_group, thread_name, callback = std::move(callback)]() -> Result
|
|
|
|
{
|
|
|
|
if (thread_group)
|
|
|
|
CurrentThread::attachTo(thread_group);
|
|
|
|
|
|
|
|
SCOPE_EXIT_SAFE({
|
2022-03-16 18:41:41 +00:00
|
|
|
if (thread_group)
|
2022-09-07 15:44:29 +00:00
|
|
|
CurrentThread::detachQueryIfNotDetached();
|
2022-03-16 18:41:41 +00:00
|
|
|
});
|
2022-09-07 15:44:29 +00:00
|
|
|
|
|
|
|
setThreadName(thread_name.data());
|
|
|
|
|
|
|
|
return callback();
|
|
|
|
});
|
|
|
|
|
|
|
|
auto future = task->get_future();
|
|
|
|
|
|
|
|
/// ThreadPool is using "bigger is higher priority" instead of "smaller is more priority".
|
|
|
|
pool->scheduleOrThrow([task]{ (*task)(); }, -priority);
|
|
|
|
|
|
|
|
return future;
|
2022-03-16 18:41:41 +00:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2022-09-07 15:44:29 +00:00
|
|
|
template ThreadPoolCallbackRunner<void> threadPoolCallbackRunner(ThreadPool & pool, const std::string & thread_name);
|
|
|
|
template ThreadPoolCallbackRunner<IAsynchronousReader::Result> threadPoolCallbackRunner(ThreadPool & pool, const std::string & thread_name);
|
|
|
|
|
2022-03-16 18:41:41 +00:00
|
|
|
}
|