Skip to content

Instantly share code, notes, and snippets.

@hamishforbes
Last active August 23, 2024 01:01
Show Gist options
  • Save hamishforbes/1bdc679893eabbbab3bd to your computer and use it in GitHub Desktop.
Save hamishforbes/1bdc679893eabbbab3bd to your computer and use it in GitHub Desktop.
Single backround thread in with multiple workers
error_log logs/error.log debug;
events {
worker_connections 1024;
}
worker_processes 4;
http {
default_type application/octet-stream;
lua_shared_dict test_dict 1m;
init_by_lua '
function my_bg_func(premature)
-- Set timer immediately so it will always run on the 10s mark
local ok, err = ngx.timer.at(10, my_bg_func)
if not ok then
ngx.log(ngx.ERR, "Failed to start background thread: "..err)
end
local dict = ngx.shared["test_dict"]
local lock, err = dict:add("flag", ngx.worker.pid(), 30)
if lock then
ngx.log(ngx.DEBUG, ngx.worker.pid(), " locked")
ngx.sleep(2) -- Simulate doing some work
local pid, err = dict:get("flag")
if pid == ngx.worker.pid() then
dict:delete("flag")
else
ngx.log(ngx.DEBUG, "couldnt release lock")
end
else
if err == "exists" then
return
else
ngx.log(ngx.ERR, err)
end
end
end
';
init_worker_by_lua '
local dict = ngx.shared["test_dict"]
local ok, err = ngx.timer.at(1, my_bg_func)
if not ok then
ngx.log(ngx.ERR, "Failed to start background thread: "..err)
end
';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment