.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
|