on
关于torch的threads线程池
torch中(也许是lua?)有一个自带的线程池threads,看到很多人在用,但是这个东西的工作方式还是让我纠结了一下的。
这个线程池通过addjob方法来增加任务,addjob除了自身外接受两个参数,一个是任务函数,一个是任务函数结束后的回调函数。这两个函数实际上只有任务函数是工作在线程池中的,而回调函数是串行执行的。
刚开始我以为各个回调函数之间是完全并行执行的,实际上可以理解为,在我们本身定义的线程池之外,还存在一个回调函数专用的线程池,所有回调线程都会放到这个线程池中来执行。
举例说明
local Threads = require 'threads'
local function in_thread(idx)
print(idx)
return idx
end
local function after_thread(data)
print('c@',data[1],data[2])
-- sys.sleep(1)
print('d',data[2])
end
tp = Threads(2,function () require 'sys' end)
for i=1,6 do
tp:addjob(function () print('a',__threadid,i)sys.sleep(1) return {__threadid,i} end,after_thread)
end
即任务函数执行1秒,回调函数不耗时,执行总时间大约3秒
而
local Threads = require 'threads'
local function in_thread(idx)
print(idx)
return idx
end
local function after_thread(data)
print('c@',data[1],data[2])
sys.sleep(1)
print('d',data[2])
end
tp = Threads(2,function () require 'sys' end)
for i=1,6 do
tp:addjob(function () print('a',__threadid,i) return {__threadid,i} end,after_thread)
end
即回调函数耗时一秒,任务函数不耗时,执行时间6秒。
也就是说,可以保证回调函数是被串行执行的,不必担心一致性问题。