Anoop
Anoop

Reputation: 147

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()

Upvotes: 1

Views: 1305

Answers (2)

Anoop
Anoop

Reputation: 147

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()

Upvotes: 2

Gran PC
Gran PC

Reputation: 21

You'll have to use lindas to synchronize the variable yourself - here's the documentation:

http://kotisivu.dnainternet.net/askok/bin/lanes/#lindas

And here's a fixed version of your code:

require("lanes")

shared_variable = 0

local linda = lanes.linda()

local function lane1()
    while true do
        shared_variable = shared_variable + 1
        linda:send("var", shared_variable)
    end
end

local function lane2()
    while true do
        local v = linda:receive("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()

Upvotes: 1

Related Questions