【发布时间】: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和在循环中创建你的协程之间有什么区别。 -
可以用非整数
a和b调用is_coprime(a,b,false)吗? -
@EgorSkriptunoff 是,
is_coprime()检查c是否为假,如果是,则仅比较a和b
标签: multithreading lua coroutine