PostgreSQL: cancel a query from a C / C ++ program

I use PostgreSQL 8.3 and am writing a C ++ program that uses the libpq API. I execute commands asynchronously using the PQsendQuery() function. I am trying to implement a timeout processing function. I executed it by calling PQcancel() when the timeout expired. 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 canceling the PQcancel() command, PQcancel() blocked until the server completes execution, and then will return with a successful request.

I understand that the documentation says that even with a successful request to cancel the request, the request can be fulfilled. My problem is that PQcancel() blocks my thread of execution, which is unacceptable because I use asynchronous processing (using the Boost Asio framework), so my program, which can perform other tasks besides executing the SQL query, only works on one thread.

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

+6
source share
2 answers

I looked at the implementation of PQcancel . It creates a separate TCP connection to the server, so it blocks. This piece of code is exactly the same in the newest version of PostgreSQL. Therefore, I came to the conclusion that there is no way to make it non-blocking, except to trigger the cancellation in a separate thread. This is also the preferred way to use this function, since the undo object is completely independent of the connection object, so it makes full use of threads.

+2
source

It looks like you are doing this on a blocking connection. Check the documentation for PQsetnonblocking, set the connection to non-blocking, and you should immediately return PQCancel. But he will also do all operations with a non-blocking connection.

0
source

Source: https://habr.com/ru/post/950897/


All Articles