Search code examples
c++multithreadingpostgresqllibpq

Thread safe PQconn object


I want to access a PostgreSQL table across a number of threads. How can I safeguard PQconn* object while multithreading? Does libpq library offer any method for this problem?


Solution

  • A single connection to PostgreSQL does not support simultaneous queries. When a query is active, it's not possible to reuse its PGconn structure for anything else, with the exception of PQcancel() that may be called from another thread or a signal handler.

    This comes from the design of the client-server protocol, not libpq itself.

    To implement concurrent queries within multiple threads, each thread must have its own connection and its own corresponding non-shared PGconn structure.