1
0
forked from blue/pica
pica/database/pool.cpp

58 lines
1.4 KiB
C++

//SPDX-FileCopyrightText: 2023 Yury Gubich <blue@macaw.me>
//SPDX-License-Identifier: GPL-3.0-or-later
#include "pool.h"
DB::Pool::Pool (Private):
std::enable_shared_from_this<Pool>(),
mutex(),
conditional(),
interfaces()
{}
DB::Pool::~Pool () {
}
std::shared_ptr<DB::Pool> DB::Pool::create () {
return std::make_shared<Pool>(Private());
}
void DB::Pool::addInterfaces (
Interface::Type type,
std::size_t amount,
const std::string & login,
const std::string & password,
const std::string & database,
const std::string& path
) {
std::unique_lock lock(mutex);
for (std::size_t i = 0; i < amount; ++i) {
const std::unique_ptr<Interface>& ref = interfaces.emplace(Interface::create(type));
ref->setCredentials(login, password);
ref->setDatabase(database);
ref->connect(path);
}
lock.unlock();
conditional.notify_all();
}
DB::Resource DB::Pool::request () {
std::unique_lock lock(mutex);
while (interfaces.empty())
conditional.wait(lock);
std::unique_ptr<Interface> interface = std::move(interfaces.front());
interfaces.pop();
return Resource(std::move(interface), shared_from_this());
}
void DB::Pool::free (std::unique_ptr<Interface> interface) {
std::unique_lock lock(mutex);
interfaces.push(std::move(interface));
lock.unlock();
conditional.notify_one();
}