27.14. Behavior in Threaded Programs

libpq is reentrant and thread-safe if the configure command-line option --enable-thread-safety has been used when the PostgreSQL distribution was built. In addition, you might need to use additional 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 in src/Makefile.global for PTHREAD_CFLAGS and PTHREAD_LIBS.

One restriction is that no two threads attempt to manipulate the same PGconn 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 read-only after creation, and so can be passed around freely between threads.

The deprecated functions PQrequestCancel, PQoidStatus and fe_setauthsvc are not thread-safe and should not be used in multithread programs. PQrequestCancel can be replaced by PQcancel. PQoidStatus can be replaced by PQoidValue. There is no good reason to call fe_setauthsvc at all.

libpq applications that use the crypt authentication method rely on the crypt() operating system function, which is often not thread-safe. It is better to use the md5 method, which is thread-safe on all platforms.

libpq must ignore SIGPIPE signals generated internally by send() calls to backend processes. When PostgreSQL is configured without --enable-thread-safety, libpq sets SIGPIPE to SIG_IGN before each send() call and restores the original signal handler after completion. When --enable-thread-safety is used, libpq installs its own SIGPIPE handler before the first database connection. This handler uses thread-local storage to determine if a SIGPIPE signal has been generated by a libpq send(). If an application wants to install its own SIGPIPE signal handler, it should call PQinSend() to determine if it should ignore the SIGPIPE signal. This function is available in both thread-safe and non-thread-safe versions of libpq.

If you experience problems with threaded applications, run the program in src/tools/thread to see if your platform has thread-unsafe functions. This program is run by configure, but for binary distributions your library might not match the library used to build the binaries.