6

I'm using PostgreSQL 8.3, and writing a program in C++ that uses the libpq API. I execute commands asynchronously with the PQsendQuery() function. I'm trying to implement a timeout processing feature. I implemented it by calling PQcancel() when the timeout expires. I tested it with a query that returns 100 000 rows (it lasts about 0.5 s) with a timeout of 1 ms, and found that instead of cancelling the command, PQcancel() blocks until the server finishes execution, then returns with a successful query.

I understand that the documentation says that even with a successful cancel request the query may still be executed. My problem is that PQcancel() blocks my thread of execution, which is not acceptable because I use asynchronous processing (using the Boost Asio framework) so my program, which may have other tasks to do other than executing the SQL query, runs only on one thread.

Is it normal that PQcancel() blocks? Is there any way to make a non-blocking cancel request?

4

2 回答 2

2

我查看了PQcancel. 它创建一个到服务器的单独 TCP 连接,这就是它阻塞的原因。此代码部分在最新版本的 PostgreSQL 中也完全相同。所以我得出结论,除了在单独的线程中启动取消之外,没有办法让它成为非阻塞的。这也是使用此功能的首选方式,因为取消对象完全独立于连接对象,因此使用起来完全是线程安全的。

于 2013-08-15T07:38:22.510 回答
0

听起来您是在阻塞连接上执行此操作。检查 PQsetnonblocking 的文档,将连接设置为非阻塞,您应该能够让 PQCancel 立即返回。但它也会使连接上的所有操作都成为非阻塞的。

于 2013-08-13T21:24:33.173 回答