#include <yandex/maps/wiki/threadutils/thread_pools.h>

namespace maps::wiki {

ThreadPools::Holder ThreadPools::pool(size_t threadsNumber)
{
    ASSERT(threadsNumber);
    std::lock_guard<std::mutex> lock(mutex_);

    auto& pools = threadsNumberToPools_[threadsNumber];
    if (pools.empty()) {
        return { *this, std::make_unique<ThreadPool>(threadsNumber) };
    }
    ThreadPoolPtr pool;
    pool.swap(pools.front());
    pools.pop();

    return { *this, std::move(pool) };
}

void ThreadPools::release(ThreadPoolPtr pool)
{
    std::lock_guard<std::mutex> lock(mutex_);
    auto& pools = threadsNumberToPools_[pool->threadsCount()];
    pools.emplace(std::move(pool));
}

} //namespace maps::wiki

