【问题标题】:Sharing a variable between coroutines在协程之间共享一个变量
【发布时间】:2016-04-02 16:16:40
【问题描述】:

我正在做一个高度密集的过程,我可以分成多个coroutines,但在其中,每当我得到正确的结果时,我都需要添加到一个变量中。目前,Lua 似乎重置了我为每个线程添加的变量,给了我不正确的结果。

我环顾四周,还没有发现类似的问题。

相关代码

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

【问题讨论】:

  • @NicolBolas,对不起,我发布了旧版本,没有包含声明。 s 似乎每次运行时都会重置。
  • 因为你的协程实际上从来没有产生过,所以你不应该看到直接调用calc和在循环中创建你的协程之间有什么区别。
  • 可以用非整数ab调用is_coprime(a,b,false)吗?
  • @EgorSkriptunoff 是,is_coprime() 检查c 是否为假,如果是,则仅比较ab

标签: multithreading lua coroutine


【解决方案1】:

感谢@NicolBolas 的评论,我放弃了所有协程,只使用更小的缓冲区循环所有内容。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-09
    • 1970-01-01
    • 1970-01-01
    • 2013-06-20
    • 2012-11-14
    • 1970-01-01
    相关资源
    最近更新 更多