简体   繁体   中英

How to avoid dead lock while using advisory locks in postgresql

I'm using the pg_advisory_lock function in postgres which blocks/waits if it's not able to get a lock on a particular key. I was wondering if there is some way to get a timeout on this? I couldn't find anything with what I've looked. If not, is there a way for a session to force release a lock obtained by a different session?

Thanks!

If you don't want to block at all, you can just call pg_try_advisory_lock() .

If a blocking pg_advisory_lock() call does result in a deadlock, it will automatically time out after the interval specified by the deadlock_timeout setting (one second by default). You can also limit the lock wait time - deadlocked or not - by setting lock_timeout (which by default is disabled).

Note that triggering either of these timeouts will raise an error, so it may be useful to wrap the error handling in a function, eg:

CREATE FUNCTION pg_try_advisory_lock_with_timeout(key bigint) RETURNS boolean
SET lock_timeout TO '1s'
AS $$
BEGIN
  PERFORM pg_advisory_lock(key);
  RETURN true;
EXCEPTION
  WHEN lock_not_available OR deadlock_detected THEN
    RETURN false;
END;
$$
LANGUAGE plpgsql;

You can try idle_in_transaction_session_timeout

Terminate any session with an open transaction that has been idle fora longer than the specified duration in milliseconds. This allows any locks held by that session to be released and the connection slot to be reused; it also allows tuples visible only to this transaction to be vacuumed. See Section 24.1 for more details about this.

Assume you run Task A --> set lock resource X and set idle_in_transaction_session_timeout=1s --> if task A idle > 1s, then task A is automatically terminated and lock X is automatically released. Then task B can get the lock X.

By this way, you can avoid deadlock of resource X.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM