转载请注明出处:
http://www.cnblogs.com/darkknightzh/p/6549452.html
参考网址:
https://github.com/torch/threads#examples
1. addjob简单示例
参考网址中给出了torch中threads的addjob函数使用方法:
local threads = require 'threads' local nthread =
local njob =
local msg = "hello from a satellite thread" local pool = threads.Threads(
nthread,
function(threadid)
print('starting a new thread/state number ' .. threadid)
gmsg = msg -- get it the msg upvalue and store it in thread state
end
) local jobdone =
for i=,njob do
pool:addjob(
function() -- note1
print(string.format('%s -- thread ID is %x', gmsg, __threadid))
return __threadid
end,
function(id)
print(string.format("task %d finished (ran on thread ID %x)", i, id))
jobdone = jobdone +
end
-- note2
)
end pool:synchronize()
print(string.format('%d jobs done', jobdone))
pool:terminate()
上面程序是一个简单的例子。
2. addjob传入参数
note1的地方,当该函数无输入参数时,直接那样写,同时note2处什么也不写。
如果note1的function需要传入参数,可以写上参数列表,同时在note2处加上参数。如下所示:
pool:addjob(
function(variable1, variable2, bariable3) -- note1
-- code …
end,
function(id)
-- code …
end,
var1, -- note2
var2,
var3
)
3. addjob函数说明
addjob函数如下:
Threads:addjob([id], callback, [endcallback], [...])
callback为在队列线程中执行的函数,endcallback为在主线程中执行的函数。