我正在尝试设置一个玩具示例,用于在火炬中进行线程化但是我在运行下面的代码时收到错误。我想这可能只是我设置表格的方式,但我不确定。
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()
中。但是,稍后在:addjob()
函数中调用相同的:getBatch()
可以正常工作。在设置metatable之前,我是否不允许调用._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
答案 0 :(得分:1)
当new
函数中的代码运行时,metatable尚未设置,所以当您使用self._getFromThreads
和self._pushResult
时,那里没有任何内容,而您得到nil
,但这无效。
new
函数返回后工作因为此时已添加metatable,所以查找使用__index
元方法查找条目。
你可以做到
local self = setmetatable({}, DataThreads)
立即设置metatable,然后
return self
最后。