pg.ddx.io  pgsql-general@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Stephen Frost <sfrost@snowman.net>
To: Enrico Thierbach <eno@open-lab.org>
Cc: pgsql-general@lists.postgresql.org
Subject: Re: SELECT .. FOR UPDATE: find out who locked a row
Date: Thu, 15 Mar 2018 16:48:51 -0400
Message-ID: <20180315204851.GU2416@tamriel.snowman.net> (raw)
In-Reply-To: <E269BF34-4CE1-47EC-8A80-F18DE55E2BEF@open-lab.org>
References: <E269BF34-4CE1-47EC-8A80-F18DE55E2BEF@open-lab.org>

Greetings,

* Enrico Thierbach (eno@open-lab.org) wrote:
> I am using `SELECT * FROM queue ... FOR UPDATE SKIP LOCKED` to implement a
> queueing system.
> 
> Now I wonder if it is possible, given the id of one of the locked rows in
> the queue table, to find out which connection/which transaction owns the
> lock.

Sure, you can attempt to lock the record and then run pg_blocking_pids()
(in another session) against the pid which is trying to acquire the
lock.

Session #1:

Connect
SELECT * FROM queue ... FOR UPDATE SKIP LOCKED;
... gets back some id X
... waits

Session #2:

Connect
SELECT pg_backend_pid(); -- save this for the 3rd session
SELECT * FROM queue WHERE id = X FOR UPDATE;
... get blocked waiting for #1
... waits

Session #3:

SELECT pg_blocking_pids(SESSION_2_PID);
-- returns PID of Session #1

Obviously there's race conditions and whatnot (what happens if session
#1 releases the lock?), but that should work to figure out who is
blocking who.

If you're on a version of PG without pg_blocking_pids then you can look
in the pg_locks view, though that's a bit more annoying to decipher.

Thanks!

Stephen

Attachments:

  signature.asc (application/pgp-signature, 818B) download

view thread (19+ messages)  latest in thread

Message-ID: <20180315204851.GU2416@tamriel.snowman.net>
Permalink:  ../20180315204851.GU2416@tamriel.snowman.net/
Also on:    postgresql.org/message-id/20180315204851.GU2416@tamriel.snowman.net

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients from your mail client; the link fills in
  the headers below: reply via email
  Some clients, webmail especially, drop In-Reply-To and References from
  a link, and the reply then starts a new thread: use the mbox below.

  To: pgsql-general@postgresql.org
  Cc: sfrost@snowman.net, eno@open-lab.org
  Subject: Re: SELECT .. FOR UPDATE: find out who locked a row
  In-Reply-To: <20180315204851.GU2416@tamriel.snowman.net>
  References: <E269BF34-4CE1-47EC-8A80-F18DE55E2BEF@open-lab.org> <20180315204851.GU2416@tamriel.snowman.net>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox