31.19. Behavior in Threaded Programs
libpq is reentrant and thread-safe by default. You might need to use special compiler command-line options when you compile your application code. Refer to your system's documentation for information about how to build thread-enabled applications, or look insrc/Makefile.global
forPTHREAD_CFLAGS
andPTHREAD_LIBS
. This function allows the querying oflibpq's thread-safe status:
One thread restriction is that no two threads attempt to manipulate the samePGconn
object at the same time. In particular, you cannot issue concurrent commands from different threads through the same connection object. (If you need to run concurrent commands, use multiple connections.)
PGresult
objects are normally read-only after creation, and so can be passed around freely between threads. However, if you use any of thePGresult
-modifying functions described inSection 31.11 orSection 31.13, it's up to you to avoid concurrent operations on the samePGresult
, too.
The deprecated functionsPQrequestCancel
andPQoidStatus
are not thread-safe and should not be used in multithread programs.PQrequestCancel
can be replaced byPQcancel
.PQoidStatus
can be replaced byPQoidValue
.
If you are using Kerberos inside your application (in addition to insidelibpq), you will need to do locking around Kerberos calls because Kerberos functions are not thread-safe. See functionPQregisterThreadLock
in thelibpq source code for a way to do cooperative locking betweenlibpq and your application.