ClickHouse/dbms/include/DB/Common/PoolBase.h

157 lines
4.5 KiB
C++
Raw Normal View History

2015-10-05 01:26:43 +00:00
#pragma once
#include <mutex>
#include <condition_variable>
2015-10-05 01:26:43 +00:00
#include <Poco/Timespan.h>
#include <boost/noncopyable.hpp>
#include <common/logger_useful.h>
/// This type specifies the possible behaviors of an object pool allocator.
2016-03-01 17:47:53 +00:00
enum class PoolMode
{
/// Get exactly one object from a given pool.
2016-03-01 17:47:53 +00:00
GET_ONE = 0,
/// Get a number of objects from a given pool, this number being
/// read from a configuration parameter.
2016-03-01 17:47:53 +00:00
GET_MANY,
/// Get all the objects from a given pool.
2016-03-01 17:47:53 +00:00
GET_ALL
};
2015-10-05 01:26:43 +00:00
/** Класс, от которого можно унаследоваться и получить пул чего-нибудь. Используется для пулов соединений с БД.
* Наследник должен предоставить метод для создания нового объекта для помещения в пул.
*/
template <typename TObject>
class PoolBase : private boost::noncopyable
{
public:
using Object = TObject;
using ObjectPtr = std::shared_ptr<Object>;
using Ptr = std::shared_ptr<PoolBase<TObject>>;
2015-10-05 01:26:43 +00:00
private:
/** Объект с флагом, используется ли он сейчас. */
struct PooledObject
{
PooledObject(std::condition_variable & available_, ObjectPtr object_)
2015-10-05 01:26:43 +00:00
: object(object_), available(available_)
{
}
ObjectPtr object;
bool in_use = false;
std::condition_variable & available;
2015-10-05 01:26:43 +00:00
};
using Objects = std::vector<std::shared_ptr<PooledObject>>;
2015-10-05 01:26:43 +00:00
/** Помощник, который устанавливает флаг использования объекта, а в деструкторе - снимает,
* а также уведомляет о событии с помощью condvar-а.
*/
struct PoolEntryHelper
{
PoolEntryHelper(PooledObject & data_) : data(data_) { data.in_use = true; }
~PoolEntryHelper() { data.in_use = false; data.available.notify_one(); }
2015-10-05 01:26:43 +00:00
PooledObject & data;
};
public:
/** То, что выдаётся пользователю. */
class Entry
{
public:
friend class PoolBase<Object>;
Entry() {} /// Для отложенной инициализации.
/** Объект Entry защищает ресурс от использования другим потоком.
* Следующие методы запрещены для rvalue, чтобы нельзя было написать подобное
*
2016-02-03 21:37:52 +00:00
* auto q = pool.Get()->query("SELECT .."); // Упс, после этой строчки Entry уничтожился
2015-10-05 01:26:43 +00:00
* q.execute(); // Кто-то еще может использовать этот Connection
*/
Object * operator->() && = delete;
const Object * operator->() const && = delete;
Object & operator*() && = delete;
const Object & operator*() const && = delete;
Object * operator->() & { return &*data->data.object; }
const Object * operator->() const & { return &*data->data.object; }
Object & operator*() & { return *data->data.object; }
const Object & operator*() const & { return *data->data.object; }
bool isNull() const { return data == nullptr; }
2015-10-05 01:26:43 +00:00
private:
std::shared_ptr<PoolEntryHelper> data;
2015-10-05 01:26:43 +00:00
Entry(PooledObject & object) : data(std::make_shared<PoolEntryHelper>(object)) {}
2015-10-05 01:26:43 +00:00
};
virtual ~PoolBase() {}
/** Выделяет объект для работы. При timeout < 0 таймаут бесконечный. */
Entry get(Poco::Timespan::TimeDiff timeout)
{
std::unique_lock<std::mutex> lock(mutex);
2015-10-05 01:26:43 +00:00
while (true)
{
for (auto & item : items)
if (!item->in_use)
return Entry(*item);
2015-10-05 01:26:43 +00:00
if (items.size() < max_items)
{
ObjectPtr object = allocObject();
items.emplace_back(std::make_shared<PooledObject>(available, object));
2015-10-05 01:26:43 +00:00
return Entry(*items.back());
}
LOG_INFO(log, "No free connections in pool. Waiting.");
if (timeout < 0)
available.wait(lock);
2015-10-05 01:26:43 +00:00
else
available.wait_for(lock, std::chrono::microseconds(timeout));
2015-10-05 01:26:43 +00:00
}
}
void reserve(size_t count)
{
std::lock_guard<std::mutex> lock(mutex);
2015-10-05 01:26:43 +00:00
while (items.size() < count)
items.emplace_back(std::make_shared<PooledObject>(available, allocObject()));
2015-10-05 01:26:43 +00:00
}
private:
/** Максимальный размер пула. */
unsigned max_items;
/** Пул. */
Objects items;
/** Блокировка для доступа к пулу. */
std::mutex mutex;
std::condition_variable available;
2015-10-05 01:26:43 +00:00
protected:
Logger * log;
PoolBase(unsigned max_items_, Logger * log_)
: max_items(max_items_), log(log_)
{
items.reserve(max_items);
}
/** Создает новый объект для помещения в пул. */
virtual ObjectPtr allocObject() = 0;
};