数据库编程接口Libpq 3

来源:互联网 发布:ubuntu看视频花屏 编辑:程序博客网 时间:2024/05/01 08:55

.10 在多线程程序中使用libpq    libpq的函数是线程安全的,可以在多线程程序中使用libpq。但编译libpq共享库时,必须使用特殊的选项才能保证生成的libpq共享库是线程安全的。Libpq提供了一个特殊的函数PQisthreadsafe,应用程序可以调用这个函数确定自己使用的libpq共享库是不是线程安全的。


PQisthreadsafe

返回1表示libpq共享库是线程安全的,返回0表示libpq共享库不是线程安全的.
       int PQisthreadsafe();

两个线程不能同时处理同一个PGconn对象,两个线程不能在同一个数据库连接上同时发SQL命令给数据库执行。多个线程如果想同时执行SQL命令,每个线程最好使用不同的数据库连接


PGresult对象在被创建以后就变成只读的,可以在多个线程之间自由地传递PGresult对象。

第十一节
编译和链接 libpq 程序



1.11 编译和链接 libpq
程序

使用下面的步骤编译和链接libpq
程序:

(1)
包含libpq-fe.h
头文件
#include <libpq-fe.h>如果没有包含libpq-fe.h
头文件,编译libpq
程序时会得到类似下面的错误:

foo.c: In function `main':foo.c:34: `PGconn' undeclared (first use in this function)foo.c:35: `PGresult' undeclared (first use in this function)foo.c:54: `CONNECTION_BAD' undeclared (first use in this function)foo.c:68: `PGRES_COMMAND_OK' undeclared (first use in this function)foo.c:95: `PGRES_TUPLES_OK' undeclared (first use in this function)(2)
使用-Idirectory
选项告诉编译器存放libpq-fe.h
头文件的目录,例如:
cc -c -I/usr/local/pgsql/include testprog.c如果使用makefile来编译程序,把下面的选项加到CPPFLAGS变量中:
CPPFLAGS += -I/usr/local/pgsql/include可以使用数据库提供的工具pg_config来确定libpq-fe.h
头文件所在的目录,在操作系统中执行下面的命令即可:

$ pg_config --includedir/usr/local/include如果编译器找不到libpq-fe.h
头文件,会报类似下面的错误:

testlibpq.c:8:22: libpq-fe.h: No such file or directory(3)
链接libpq
程序时,必须使用选项-lpq-Ldirectory选项-Ldirectory指出存放libpq共享库文件的目录。注意,为了提高兼容性,-Ldirectory应该出现在-lpq的前面。例如:
cc -o testprog testprog1.o testprog2.o -L/usr/local/pgsql/lib -lpq可以使用数据库提供的工具pg_config来确定存放libpq共享库文件的目录:
$ pg_config --libdir/usr/local/pgsql/lib如果没使用-lpq选项,会遇到类似下面的错误:
testlibpq.o: In function `main':testlibpq.o(.text+0x60): undefined reference to `PQsetdbLogin'testlibpq.o(.text+0x71): undefined reference to `PQstatus'testlibpq.o(.text+0xa4): undefined reference to `PQerrorMessage'如果-Ldirectory选项指定的存放libpq共享库文件的目录不正确,会遇到下面的错误:
/usr/bin/ld: cannot find -lpq