ngx.sleep() vs semaphore:wait() for sleeping in a tight loop?

10 views
Skip to first unread message

Ben Wilber

unread,
Nov 29, 2022, 12:04:19 PM11/29/22
to openresty-en
Hello,

I have a location that runs a very tight loop holding open connections and sending response data incrementally as it's received elsewhere.  I would like to wait between iterations and thought to use ngx.sleep() but my understanding is that it uses timers internally which can quickly become exhausted.  What about waiting on a semaphore instead?  Assuming that it can never be acquired, :wait() with a timeout would serve as a better "sleep" mechanism?  Thank you!

Example code:

init_worker_by_lua_block {
    local semaphore = require "ngx.semaphore"

    -- Can never be acquired (ie, never :post()'d)
    SLEEP_LOCK = semaphore.new(0)
}

location = /tight-loop {
    content_by_lua_block {
      local sleep_lock = SLEEP_LOCK -- global in the worker

      ngx.status = ngx.HTTP_OK
      ngx.header["Content-Type"] = "text/plain"

      for i=1, math.huge do
        ngx.say(("Iter: %d\n"):format(i))
        ngx.flush(true)

        -- Which is better for "sleeping" between iterations?
        -- Assuming a very large number of clients (1M+) are in the tight loop

        ngx.sleep(0.010)

        -- Or:

        sleep_lock:wait(0.010)
      end
    }
}
Reply all
Reply to author
Forward
0 new messages