Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New atomic functions(cas, cog) for shm #1954

Open
Miniwoffer opened this issue Oct 28, 2021 · 0 comments
Open

New atomic functions(cas, cog) for shm #1954

Miniwoffer opened this issue Oct 28, 2021 · 0 comments

Comments

@Miniwoffer
Copy link
Contributor

Miniwoffer commented Oct 28, 2021

Proposal

Add two new functions to shm

ngx.shared.DICT.cog


syntax: value, flags = ngx.shared.DICT:cog(key, old_value?, old_flags?)

Similar to the get method, but only returns if
old_value or old_flags do not match.

If old_value or old_flags is nil
it will be ignored when comparing.

In case of match, nil, false will be returned.

ngx.shared.DICT.cas


syntax: success, err, forcible = ngx.shared.DICT:cas(key, old_value?, old_flags?, value?, flags?, exptime?)

Conditionally sets key-value pair in shm.

If old_value or old_flags is nil it will
be ignored.

If either value or flags is nil it will
remain unchanged. If both are nil, key-value pair will be deleted.

In case of mismatch, false, false will be returned.

Example usage

cog

local lru = require "resty.lrucache".new(100)
local cjson = require "cjson.safe"
local shm = ngx.shared.config

local function get(key)
        local lru_data, _, lru_flag = lru:get(key)

        local shm_data, shm_flag = shm:cog(key, nil, lru_flag)
        if not shm_data then
                if shm_flag == false then -- boolean false returned on no-error
                        return lru_data
                end

                return nil, shm_flag
        end

        local val, err = cjson.decode(shm_data)
        if not val then
                return nil, err
        end

        lru:set(key, val, nil, shm_flag)

        return val, shm_flag
end

cas

local shm = ngx.shared.config
local function multiply(key, factor)
        for _=1,100 do
                local val, flags = shm:get(key)

                if not val then
                        return shm:set(key, 1, nil, 1)
                end

                local ok, err = shm:cas(key, nil, flags, val * factor, flags+1)

                if ok then
                        return ok
                end

                if err ~= false then
                        return nil, err
                end

                ngx.sleep(0.0001)
        end

        return nil, "out of tries"
end

Pull requests

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant