inter-process lock via ngx.shared.DICT.add/delete

64 views
Skip to first unread message

Russell Sullivan

unread,
Oct 6, 2017, 7:58:30 PM10/6/17
to openresty-en

I need a nginx-wide (i.e. multiple processes) lock.

My plan is to use a ngx.shared.DICT and methods: add (w/ sleep on failure) and delete around the non 'thread"-safe code

pseudocode would be:
local finished = false; 
while (not finished) do
  local success, err, forcible = ngx.shared.DICT.add("LOCK", 1);  
  if (not success and err == "exists") then
    ngx.sleep(0);    -- LOCK FAILED TRY AGAIN (NEXT NGINX EVENT LOOP)
  else
    finished = true; -- LOCK SUCCESS
  end
end
<<CODE>>
ngx.shared.DICT.delete("LOCK");

Will this work correctly? (conceptually: i.e. ignore that its pseudo-code and that I dont check all errors from the add() call)

Is it a hack? Are there some bad side effects (other than on lock fail the co-routine sleeping some)?

Is there a better way to do this

thanks :)

tokers

unread,
Oct 7, 2017, 3:41:05 AM10/7/17
to openresty-en
Hi!
I think the https://github.com/openresty/lua-resty-lock is the best choice which is light-weight. Actually it also based on the ngx.shared.DICT.

Russell Sullivan

unread,
Oct 7, 2017, 9:45:55 PM10/7/17
to openresty-en

@tokers THANKS ... I somehow missed finding lua-resty-lock :)

always better to use something established and tested than to build your own
Reply all
Reply to author
Forward
0 new messages