Guest User

ParallelPrograms

a guest
Jun 8th, 2020
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.06 KB | None | 0 0
  1. local com = require('component')
  2. local cmp = require('computer')
  3. local evt = require('event')
  4. local cor = coroutine
  5.  
  6. local last_gpu = 0
  7. local gpu_addrs = {}
  8. local threads = {}
  9. local mt_thread = {}
  10.  
  11. local DEBUG_MODE = false
  12.  
  13. -- copy GPU addresses to table
  14. for k in com.list('gpu', true) do table.insert(gpu_addrs, k) end
  15.  
  16. io.write("Commands: ")
  17. local cmd = io.read()
  18. io.write("Count: ")
  19. local cnt = tonumber(io.read())
  20.  
  21. cmd = (cmd .. ' '):rep(cnt or 1)
  22.  
  23. for v in cmd:gmatch('%S+') do
  24.   io.write('Arguments for ' .. tostring(v) .. ': ')
  25.   local args = io.read()
  26.  
  27.   -- replace %GPU% in arguments with real GPU address
  28.   while args:match('%%GPU%%') do
  29.     last_gpu = last_gpu + 1
  30.     if last_gpu > #gpu_addrs then last_gpu = 1 end
  31.     local gpu_addr = tostring(gpu_addrs[last_gpu] or "nil")
  32.     print(tostring(v) .. ' - %GPU% found, substituting GPU address: ' .. gpu_addr:sub(1, 10) .. '...')
  33.     args = args:gsub('%%GPU%%', gpu_addr, 1)
  34.   end
  35.  
  36.   local t = {}
  37.   t.thread = cor.create(function() os.execute(v .. ' ' .. args) end)
  38.   t.is_ready = true
  39.   t.yield_data = {}
  40.   table.insert(threads, t)
  41. end
  42.  
  43. local _pullSignal = cmp.pullSignal
  44. cmp.pullSignal = cor.yield
  45. while #threads > 0 do
  46.   -- execute ALL threads with the last event, if its name matches their event filter
  47.   local le = {_pullSignal(0)}
  48.   local t_idx = 1
  49.   while t_idx <= #threads do
  50.     local ct = threads[t_idx]
  51.     local has_timeout = tonumber(ct.yield_data[1]) and 1 or 0
  52.     if ct.is_ready or le[1] == (ct.yield_data[has_timeout + 1] or le[1]) then
  53.       ct.yield_data = table.pack(cor.resume(ct.thread, table.unpack(le)))
  54.      
  55.       if DEBUG_MODE then print('Thread', t_idx, 'yield data:', table.unpack(ct.yield_data)) end
  56.       if not table.remove(ct.yield_data, 1) or cor.status(ct.thread) == "dead" then
  57.         table.remove(threads, t_idx)
  58.         if DEBUG_MODE then print('Thread', t_idx, 'removed from list') end
  59.         t_idx = t_idx - 1
  60.       end
  61.      
  62.       ct.is_ready = (ct.yield_data.n == 0)
  63.     end
  64.     t_idx = t_idx + 1
  65.   end
  66. end
  67. cmp.pullSignal = _pullSignal
Add Comment
Please, Sign In to add comment