[odb-users] safe usage odb connection pool in multi threaded environment (odb 2.4.0)

Пустовалов Дмитрий pustovalovdmit at gmail.com
Fri Apr 28 04:23:13 EDT 2017


I want to figure out a proper way to manage database connection pool
assuming I want to use connection in different threads.

As far as I understand I should do it like this:

static constexpr auto max_connections = 20;

// 1) create connection pool

auto pool = std::make_unique<odb::mysql::connection_pool_factory>(max_connections);

// 2) bind it to database passing connection pool to odb::database constructor

auto db = std::make_unique<odb::mysql::database>(user, password,
db_name, host, 0, nullptr, "utf8", 0, std::move(pool));

// 3) get available connection_ptr from pool

auto conn = db->connection();

// 4) use connection_ptr (possibly on other thread)

std::thread t([&conn]()


    auto& db = conn1->database();

    odb::transaction t{conn1->begin()};




Is there a right way to accomplish my goal?

I have few doubts in correctness and safety of code in lambda passed to thread:

1) When I pass transaction_impl (result of odb::connection::begin) to
odb::transaction constructor does queries work on that connection not
on some default odb::database connection

2) If I work directly with odb::connection assigned to connection pool
does all queries work on one single default (first created?)
connection from this pool.

3) Is it safe to use odb::database object concurrently without mutex
protection if I get reference to it from connection (from
odb::connection::database function). I mean I need odb::database
interface in different threads, plain query interface of
odb::conenction is not enough.

Thanks in advance!

More information about the odb-users mailing list