/usr/share/lua/5.1/luacheck/multithreading.lua is in lua-check 0.13.0-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | local utils = require "luacheck.utils"
local multithreading = {}
local ok, lanes = pcall(require, "lanes")
ok = ok and pcall(lanes.configure)
multithreading.has_lanes = ok
multithreading.lanes = lanes
if not ok then
return multithreading
end
-- Worker thread reads pairs {outkey, arg} from inkey channel of linda,
-- applies func to arg and sends result to outkey channel of linda
-- until arg is nil.
local function worker_task(linda, inkey, func)
while true do
local _, pair = linda:receive(nil, inkey)
local outkey, arg = pair[1], pair[2]
if arg == nil then
return true
end
linda:send(nil, outkey, func(arg))
end
end
local worker_gen = lanes.gen("*", worker_task)
-- Maps func over array, performing at most jobs calls in parallel.
function multithreading.pmap(func, array, jobs)
jobs = math.min(jobs, #array)
if jobs < 2 then
return utils.map(func, array)
end
local workers = {}
local linda = lanes.linda()
for i = 1, jobs do
workers[i] = worker_gen(linda, 0, func)
end
for i, item in ipairs(array) do
linda:send(nil, 0, {i, item})
end
for _ = 1, jobs do
linda:send(nil, 0, {})
end
local results = {}
for i in ipairs(array) do
local _, result = linda:receive(nil, i)
results[i] = result
end
for _, worker in ipairs(workers) do
assert(worker:join())
end
return results
end
return multithreading
|