View pg_stat_activity slow to get up to date

From: "D'Arcy J(dot)M(dot) Cain" <darcy(at)druid(dot)net>
To: pgsql-hackers(at)postgresql(dot)org
Subject: View pg_stat_activity slow to get up to date
Date: 2004-11-08 17:03:52
Message-ID: 20041108120352.4ff08925.darcy@druid.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

I checked the FAQ and docs but haven't found anything definitive. This
is my SQL test script:

SELECT pg_backend_pid();
SELECT * FROM pg_stat_activity order by procpid;

When I run psql reading that I find that my backend procpid is not in
the list. I know that I can see it if I can introduce a little sleep (1
second) between the connection and the reading of pg_stat_activity.

My question is this. Is there a more reliable way to see if a
particular backend is still alive? I am trying to do a locking system
and this is necessary to make it work. I think that in actual sessions
I will be OK but my unit test fails most of the time because of this.

I will explain my scheme in case there is a better way to do what I
want. Note that using transactions won't work in my application because
I never know if I am already in one or not or if one will start while I
am in this process. What I do is create a table that has, among other
things, a serial, primary key and a pid_lock field. I add a rule like
this:

CREATE OR REPLACE RULE session_pid_lock AS
ON UPDATE TO session
WHERE EXISTS (
SELECT 1
FROM pg_stat_activity
WHERE pg_stat_activity.procpid = old.pid_lock AND
pg_stat_activity.procpid != pg_backend_pid())
DO INSTEAD NOTHING;

Now all I do to grab the lock is update pid_lock with my own backend
PID. I then test it to see if it has mine or someone else's. Now I
know whether to fail, retry or whatever. As soon as the first DB
connection drops I can grab the lock.

Right now I am modifying my lock class (It's in Python) to add a 1
second sleep before trying to grab an existing session. That seems to
work but I hope I can do better.

--
D'Arcy J.M. Cain <darcy(at)druid(dot)net> | Democracy is three wolves
http://www.druid.net/darcy/ | and a sheep voting on
+1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner.

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Anand Kumria 2004-11-08 17:18:56 Re: [PATCHES] CVS should die
Previous Message Andrew Dunstan 2004-11-08 17:03:49 latest cygwin build failure