Skip to content

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

Open
@Miniwoffer

Description

@Miniwoffer

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions