ThreadPool.cpp 7.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <Common/ThreadPool.h>
#include <Common/Exception.h>

#include <type_traits>


namespace DB
{
    namespace ErrorCodes
    {
        extern const int CANNOT_SCHEDULE_TASK;
    }
}
14

A
Alexey Milovidov 已提交
15 16 17 18 19 20 21 22
namespace CurrentMetrics
{
    extern const Metric GlobalThread;
    extern const Metric GlobalThreadActive;
    extern const Metric LocalThread;
    extern const Metric LocalThreadActive;
}

23 24

template <typename Thread>
K
kreuzerkrieg 已提交
25 26
ThreadPoolImpl<Thread>::ThreadPoolImpl(size_t max_threads_)
    : ThreadPoolImpl(max_threads_, max_threads_, max_threads_)
27 28 29 30
{
}

template <typename Thread>
31 32 33 34 35
ThreadPoolImpl<Thread>::ThreadPoolImpl(size_t max_threads_, size_t max_free_threads_, size_t queue_size_, bool shutdown_on_exception_)
    : max_threads(max_threads_)
    , max_free_threads(max_free_threads_)
    , queue_size(queue_size_)
    , shutdown_on_exception(shutdown_on_exception_)
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
template <typename Thread>
void ThreadPoolImpl<Thread>::setMaxThreads(size_t value)
{
    std::lock_guard lock(mutex);
    max_threads = value;
}

template <typename Thread>
void ThreadPoolImpl<Thread>::setMaxFreeThreads(size_t value)
{
    std::lock_guard lock(mutex);
    max_free_threads = value;
}

template <typename Thread>
void ThreadPoolImpl<Thread>::setQueueSize(size_t value)
{
    std::lock_guard lock(mutex);
    queue_size = value;
}


61
template <typename Thread>
62 63
template <typename ReturnType>
ReturnType ThreadPoolImpl<Thread>::scheduleImpl(Job job, int priority, std::optional<uint64_t> wait_microseconds)
64
{
65
    auto on_error = [&]
66 67
    {
        if constexpr (std::is_same_v<ReturnType, void>)
68 69 70 71 72 73 74
        {
            if (first_exception)
            {
                std::exception_ptr exception;
                std::swap(exception, first_exception);
                std::rethrow_exception(exception);
            }
75
            throw DB::Exception("Cannot schedule a task", DB::ErrorCodes::CANNOT_SCHEDULE_TASK);
76
        }
77 78 79 80
        else
            return false;
    };

81
    {
82 83 84 85
        std::unique_lock lock(mutex);

        auto pred = [this] { return !queue_size || scheduled_jobs < queue_size || shutdown; };

86
        if (wait_microseconds)  /// Check for optional. Condition is true if the optional is set and the value is zero.
87 88 89 90 91 92 93
        {
            if (!job_finished.wait_for(lock, std::chrono::microseconds(*wait_microseconds), pred))
                return on_error();
        }
        else
            job_finished.wait(lock, pred);

94
        if (shutdown)
95
            return on_error();
96 97

        jobs.emplace(std::move(job), priority);
98
        ++scheduled_jobs;
99

100 101 102 103 104 105 106 107 108 109
        if (threads.size() < std::min(max_threads, scheduled_jobs))
        {
            threads.emplace_front();
            try
            {
                threads.front() = Thread([this, it = threads.begin()] { worker(it); });
            }
            catch (...)
            {
                threads.pop_front();
110 111 112 113 114 115 116 117 118

                /// Remove the job and return error to caller.
                /// Note that if we have allocated at least one thread, we may continue
                /// (one thread is enough to process all jobs).
                /// But this condition indicate an error nevertheless and better to refuse.

                jobs.pop();
                --scheduled_jobs;
                return on_error();
119 120
            }
        }
121 122
    }
    new_job_or_shutdown.notify_one();
123 124 125 126
    return ReturnType(true);
}

template <typename Thread>
127
void ThreadPoolImpl<Thread>::scheduleOrThrowOnError(Job job, int priority)
128 129 130 131 132
{
    scheduleImpl<void>(std::move(job), priority, std::nullopt);
}

template <typename Thread>
133
bool ThreadPoolImpl<Thread>::trySchedule(Job job, int priority, uint64_t wait_microseconds) noexcept
134 135 136 137 138 139 140 141
{
    return scheduleImpl<bool>(std::move(job), priority, wait_microseconds);
}

template <typename Thread>
void ThreadPoolImpl<Thread>::scheduleOrThrow(Job job, int priority, uint64_t wait_microseconds)
{
    scheduleImpl<void>(std::move(job), priority, wait_microseconds);
142 143 144 145 146 147
}

template <typename Thread>
void ThreadPoolImpl<Thread>::wait()
{
    {
148 149
        std::unique_lock lock(mutex);
        job_finished.wait(lock, [this] { return scheduled_jobs == 0; });
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169

        if (first_exception)
        {
            std::exception_ptr exception;
            std::swap(exception, first_exception);
            std::rethrow_exception(exception);
        }
    }
}

template <typename Thread>
ThreadPoolImpl<Thread>::~ThreadPoolImpl()
{
    finalize();
}

template <typename Thread>
void ThreadPoolImpl<Thread>::finalize()
{
    {
170
        std::unique_lock lock(mutex);
171 172 173 174 175 176 177 178 179 180 181 182 183 184
        shutdown = true;
    }

    new_job_or_shutdown.notify_all();

    for (auto & thread : threads)
        thread.join();

    threads.clear();
}

template <typename Thread>
size_t ThreadPoolImpl<Thread>::active() const
{
185 186
    std::unique_lock lock(mutex);
    return scheduled_jobs;
187 188 189
}

template <typename Thread>
190
void ThreadPoolImpl<Thread>::worker(typename std::list<Thread>::iterator thread_it)
191
{
A
Alexey Milovidov 已提交
192 193 194
    CurrentMetrics::Increment metric_all_threads(
        std::is_same_v<Thread, std::thread> ? CurrentMetrics::GlobalThread : CurrentMetrics::LocalThread);

195 196 197 198 199 200
    while (true)
    {
        Job job;
        bool need_shutdown = false;

        {
201
            std::unique_lock lock(mutex);
202 203 204 205 206 207 208 209 210 211
            new_job_or_shutdown.wait(lock, [this] { return shutdown || !jobs.empty(); });
            need_shutdown = shutdown;

            if (!jobs.empty())
            {
                job = jobs.top().job;
                jobs.pop();
            }
            else
            {
A
Alexey Milovidov 已提交
212
                /// shutdown is true, simply finish the thread.
213 214 215 216 217 218 219 220
                return;
            }
        }

        if (!need_shutdown)
        {
            try
            {
A
Alexey Milovidov 已提交
221 222 223
                CurrentMetrics::Increment metric_active_threads(
                    std::is_same_v<Thread, std::thread> ? CurrentMetrics::GlobalThreadActive : CurrentMetrics::LocalThreadActive);

224 225 226 227 228
                job();
            }
            catch (...)
            {
                {
229
                    std::unique_lock lock(mutex);
230
                    if (!first_exception)
A
Alexey Milovidov 已提交
231
                        first_exception = std::current_exception(); // NOLINT
232 233
                    if (shutdown_on_exception)
                        shutdown = true;
234
                    --scheduled_jobs;
235
                }
236 237

                DB::tryLogCurrentException("ThreadPool",
238 239 240 241 242 243
                    std::string("Exception in ThreadPool(") +
                    "max_threads: " + std::to_string(max_threads)
                    + ", max_free_threads: " + std::to_string(max_free_threads)
                    + ", queue_size: " + std::to_string(queue_size)
                    + ", shutdown_on_exception: " + std::to_string(shutdown_on_exception)
                    + ").");
244

245 246 247 248 249 250 251
                job_finished.notify_all();
                new_job_or_shutdown.notify_all();
                return;
            }
        }

        {
252 253 254 255 256
            std::unique_lock lock(mutex);
            --scheduled_jobs;

            if (threads.size() > scheduled_jobs + max_free_threads)
            {
257
                thread_it->detach();
258 259 260 261
                threads.erase(thread_it);
                job_finished.notify_all();
                return;
            }
262 263 264 265 266 267 268 269 270 271 272
        }

        job_finished.notify_all();
    }
}


template class ThreadPoolImpl<std::thread>;
template class ThreadPoolImpl<ThreadFromGlobalPool>;


273 274 275 276 277
GlobalThreadPool & GlobalThreadPool::instance()
{
    static GlobalThreadPool ret;
    return ret;
}