Postgresql 中文操作指南
34.20. Behavior in Threaded Programs #
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 #
-
Returns the thread safety status of the libpq library.
-
int PQisthreadsafe();
-
Returns 1 if the libpq is thread-safe and 0 if it is not.
一个线程限制是,不允许两个线程同时尝试处理同一个 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 对象通常在创建后为只读,因此可在线程之间自由传递。但是,如果您使用 Section 34.12 或 Section 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.
如果您在应用程序中(以及在 libpq 中)使用 Kerberos,则需要锁定 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.