1

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?

Anthon
  • 69,918
  • 32
  • 186
  • 246
Kumar
  • 616
  • 1
  • 18
  • 39

1 Answers1

4

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.

Daniel Vérité
  • 58,074
  • 15
  • 129
  • 156
  • Even if i have a separate PGconn for each thread, all will access a single shared table at the same time. Hence the concurrent querying will produce undesirable results, isn't it? In that case how can i manage shared table across threads? – Kumar Mar 10 '15 at 04:53
  • It depends on the kind of access. If it's read-only, no problem. If not, [MVCC rules](http://www.postgresql.org/docs/current/static/mvcc-intro.html) apply, you have to choose an isolation level that best fits your needs and deal with the conflicts that the db engine itself cannot solve. – Daniel Vérité Mar 10 '15 at 10:48