Valkyrie
Valkyrie

Reputation: 861

Sharing a variable between coroutines

I'm doing a highly intensive process that I can split into multiple coroutines, but in them, I need to add to a variable whenever I get a correct result. Lua, currently, seems to reset the variable I'm adding to for every thread, giving me incorrect results.

I've done plenty of looking around, and haven't found another issue like this.

Relevant code

s=0

function calc(x,n)
    print(x,n)
    for a=x,n,1 do
        for b=a+1,n-1,1 do
            if is_coprime(a,b,false) then
                c=math.sqrt((a^2)+(b^2))
                if c<=b or c>n then break; end
                if is_coprime(a,b,c) then
                    s=s+1
                    break
                end
            end
        end
    end
end

function main(n)
    local t=0
    for i=1,n,n*.1 do
        co=coroutine.create(calc)
        coroutine.resume(co,i,n)
    end
    for _,v in ipairs(s) do
        t=t+1
    end
    return t
end

Upvotes: 2

Views: 669

Answers (1)

Valkyrie
Valkyrie

Reputation: 861

Thanks to @NicolBolas's comment, I ditched coroutines all together and just looped everything using smaller buffers.

function calc(x,n)
    local t={}
    for a=x,n,1 do
        for b=a+1,a^10,1 do
            if is_coprime(a,b,false) then
                c=math.sqrt((a^2)+(b^2))
                if c<=b or c>n then break; end
                if is_coprime(a,b,c) then
                    print(a,b,c)
                    t[tostring(a)..' '..tostring(b)..' '..tostring(c)]=true
                    break
                end
            end
        end
    end
    return t
end

function main(n)
    local t,s=0,{}
    for i=1,n,n*.1 do
        for k,v in pairs(calc(i,n)) do
            if s[k]==nil then
                s[k]=true
                t=t+1
            end
        end
    end
    return t
end

Upvotes: 1

Related Questions