我正在尝试为 torch 中的线程设置一个玩具示例,但运行下面的代码时出现错误。我认为这可能只是我设置 table 的方式,但我不确定。
Threads = require 'threads'
Threads.serialization('threads.sharedserialize')
DataThreads = {}
DataThreads.__index = DataThreads
local result = {}
local unpack = unpack and unpack or table.unpack
function DataThreads.new(nThreads,opt_)
local self = {}
opt_ = opt_ or {}
self.threads = Threads(nThreads,
function()
print("background stuff")
end
)
self.threads:synchronize()
-- The below for loop is causing the error but the same :addjob() works later on
for i=1, nThreads do
self.threads:addjob(self._getFromThreads, self._pushResult)
end
return setmetatable(self,DataThreads)
end
function DataThreads._getFromThreads()
x,y = torch.uniform(),torch.uniform()
return x,y
end
function DataThreads._pushResult(...)
local res = {...}
if res == nil then
self.threads:synchronize()
end
result[1] = res
end
function DataThreads:getBatch()
self.threads:addjob(self._getFromThreads, self._pushResult)
self.threads:dojob()
local res = result[1]
result[1] = nil
if torch.type(res) == 'table' then
return unpack(res)
end
print(type(res))
return res
end
d = DataThreads.new(4)
错误发生在.new函数中的:addjob()
处。但是稍后在 :getBatch()
函数中调用相同的 :addjob()
是有效的。在设置元表之前,我是否不允许调用 ._getFromThreads()、._getFromThreads()
函数?这是错误,我认为这意味着 ._getFromThreads()
没有返回任何内容;
/home/msmith/torch/install/bin/luajit: ...e/msmith/torch/install/share/lua/5.1/threads/threads.lua:215: function callback expected
stack traceback:
[C]: in function 'assert'
...e/msmith/torch/install/share/lua/5.1/threads/threads.lua:215: in function 'addjob'
threads.lua:21: in function 'new'
threads.lua:54: in main chunk
最佳答案
当您的 new
函数中的代码运行时,元表尚未设置,因此当您使用 self._getFromThreads
和 self._pushResult
那里什么也没有,你得到 nil
返回,这是无效的。
它在new
函数返回之后起作用,因为此时元表已被添加,因此查找使用__index
元方法来查找条目已增加。
你可以做到
local self = setmetatable({}, DataThreads)
立即设置元表,然后
return self
最后。
关于lua - 元表错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36020518/