FluttyProger

Threads.lua

Apr 26th, 2016
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. local computer = require("computer")
  2. computer.SingleThread = computer.pullSignal
  3. local thread = {}
  4.  
  5. local mainThread
  6. local timeouts
  7.  
  8. local function MultiThread( _timeout )
  9.   if coroutine.running()==mainThread then
  10.     local mintime = _timeout or math.huge
  11.     local co=next(timeouts)
  12.     while co do
  13.       if coroutine.status( co ) == "dead" then
  14.         timeouts[co],co=nil,next(timeouts,co)
  15.       else
  16.         if timeouts[co] < mintime then mintime=timeouts[co] end
  17.         co=next(timeouts,co)
  18.       end
  19.     end
  20.     if not next(timeouts) then
  21.       computer.pullSignal=computer.SingleThread
  22.       computer.pushSignal("AllThreadsDead")
  23.     end
  24.     local event={computer.SingleThread(mintime)}
  25.     local ok, param
  26.     for co in pairs(timeouts) do
  27.       ok, param = coroutine.resume( co, table.unpack(event) )
  28.       if not ok then timeouts={} error( param )
  29.       else timeouts[co] = param or math.huge end
  30.     end
  31.     return table.unpack(event)
  32.   else
  33.     return coroutine.yield( _timeout )
  34.   end
  35. end
  36.  
  37. function thread.init()
  38.   mainThread=coroutine.running()
  39.   timeouts={}
  40. end
  41.  
  42. function thread.create(f,...)
  43.   computer.pullSignal=MultiThread
  44.   local co=coroutine.create(f)
  45.   timeouts[co]=math.huge
  46.   local ok, param = coroutine.resume( co, ... )
  47.   if not ok then timeouts={} error( param )
  48.   else timeouts[co] = param or math.huge end
  49.   return co
  50. end
  51.  
  52. function thread.kill(co)
  53.   timeouts[co]=nil
  54. end
  55.  
  56. function thread.killAll()
  57.   timeouts={}
  58.   computer.pullSignal=computer.SingleThread
  59. end
  60.  
  61. function thread.waitForAll()
  62.   repeat
  63.   until MultiThread()=="AllThreadsDead"
  64. end
  65. -------------------------------------------------------------------------------
  66. return thread
Add Comment
Please, Sign In to add comment