libpq 默认是可重入和线程安全的。 编译应用程序代码时,您可能需要使用特殊的编译器命令行选项。 有关如何构建启用线程的应用程序的信息,请参阅系统文档,或在 src/Makefile.global 中查找 PTHREAD_CFLAGS 和 PTHREAD_LIBS。 此函数允许查询 libpq 的线程安全状态: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 in src/Makefile.global for PTHREAD_CFLAGS and PTHREAD_LIBS. This function allows the querying of libpq’s thread-safe status:
PQisthreadsafe函数返回 libpq 库的线程安全状态。如果 libpq 是线程安全的,则返回 1,否则返回 0。
一个线程限制是没有两个线程试图同时操作同一个 PGconn 对象。特别是,您不能通过同一个连接对象从不同线程发出并发命令。 (如果您需要运行并发命令,请使用多个连接。)One thread 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 对象在创建后通常是只读的,因此可以在线程之间自由传递。但是,如果您使用第 34.12 节或第 34.14 节中描述的任何 PGresult 修改函数,您也可以避免对同一 PGresult 进行并发操作。PGresult objects are normally read-only after creation, and so can be passed around freely between threads. However, if you use any of the PGresult-modifying functions described in Section 34.12 or Section 34.14, it’s up to you to avoid concurrent operations on the same PGresult, too.
不推荐使用的函数 PQrequestCancel 和 PQoidStatus 不是线程安全的,不应在多线程程序中使用。 PQrequestCancel 可以用 PQcancel 代替。 PQoidStatus 可以用 PQoidValue 代替。The deprecated functions PQrequestCancel and PQoidStatus are not thread-safe and should not be used in multithread programs. PQrequestCancel can be replaced by PQcancel. PQoidStatus can be replaced by PQoidValue.
如果您在应用程序中使用 Kerberos(除了在 libpq 内部),您将需要锁定 Kerberos 调用,因为 Kerberos 函数不是线程安全的。请参阅 libpq 源代码中的函数 PQregisterThreadLock,了解在 libpq 和您的应用程序之间进行协作锁定的方法。If you are using Kerberos inside your application (in addition to inside libpq), you will need to do locking around Kerberos calls because Kerberos functions are not thread-safe. See function PQregisterThreadLock in the libpq source code for a way to do cooperative locking between libpq and your application.