gpt4 book ai didi

multithreading - 在协程之间共享变量

转载 作者:行者123 更新时间:2023-12-03 13:04:14 25 4
gpt4 key购买 nike

我正在执行一个非常密集的过程,可以将其拆分为多个coroutine,但是在其中,只要我得到正确的结果,就需要将其添加到变量中。目前,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的评论,我将协程抛弃了,只是使用较小的缓冲区循环了所有程序。

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

关于multithreading - 在协程之间共享变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36375666/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com