Select unlocked row in Postgresql

后端 未结 14 2054
你的背包
你的背包 2020-12-13 06:20

Is there a way to select rows in Postgresql that aren\'t locked? I have a multi-threaded app that will do:

Select... order by id desc limit 1 for update
         


        
14条回答
  •  囚心锁ツ
    2020-12-13 06:48

    It appears that you are trying to do something like grab the highest priority item in a queue that is not already being taken care of by another process.

    A likely solution is to add a where clause limiting it to unhandled requests:

    select * from queue where flag=0 order by id desc for update;
    update queue set flag=1 where id=:id;
    --if you really want the lock:
    select * from queue where id=:id for update;
    ...
    

    Hopefully, the second transaction will block while the update to the flag happens, then it will be able to continue, but the flag will limit it to the next in line.

    It is also likely that using the serializable isolation level, you can get the result you want without all of this insanity.

    Depending on the nature of your application, there may be better ways of implementing this than in the database, such as a FIFO or LIFO pipe. Additionally, it may be possible to reverse the order that you need them in, and use a sequence to ensure that they are processed sequentially.

提交回复
热议问题