Search code examples
luaglobal-variablesscopelua-lanes

Sharing a global variable between Lua lanes


I wanted to share a global variable between 2 lanes,the idea is that when lane1 updates a shared variable,i should be able to get it's updated value on lane2 when it gets scheduled. Is there a solution to this?

Code Snippet below :-

shared_variable = 0
local function lane1()
    ..
    shared_variable = shared_variable + 1
end

local function lane2()
    ..
    print(shared_variable)-->shared variable is not getting updated,always prints 0
end

Thread1= lanes.gen("*",{globals = _G},lane1)
Thread2= lanes.gen("*",{globals = _G},lane2)

T1 = Thread1()
T2 = Thread2()

T1:join()
T2:join()

Solution

  • Below is the sample implementation where we can share a varible between Lanes(using set & get method)

    require("lanes")
    
    shared_variable = 0
    
    local linda = lanes.linda()
    
    local function lane1()
        while true do
            shared_variable = shared_variable + 1
            linda:set("var", shared_variable)
        end
    end
    
    local function lane2()
        while true do
            local v = linda:get("var")
            print(v)
        end
    end
    
    Thread1= lanes.gen("*",{globals = _G},lane1)
    Thread2= lanes.gen("*",{globals = _G},lane2)
    
    T1 = Thread1()
    T2 = Thread2()
    
    T1:join()
    T2:join()