Advertisement
fenixrus61

ParallelOC

Aug 21st, 2014
303
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.40 KB | None | 0 0
  1. local event = require("event")
  2.  
  3. local function create( first, ... )
  4.     if first ~= nil then
  5.         return coroutine.create(first), create( ... )
  6.     end
  7.     return nil
  8. end
  9.  
  10. local function runUntilLimit( _routines, _limit )
  11.     local count = #_routines
  12.     local living = count
  13.    
  14.     local tFilters = {}
  15.     local eventData = {}
  16.     while true do
  17.         for n=1,count do
  18.             local r = _routines[n]
  19.             if r then
  20.                 if tFilters[r] == nil or tFilters[r] == eventData[1] or eventData[1] == "terminate" then
  21.                     local ok, param = coroutine.resume( r, table.unpack(eventData) )
  22.                     if not ok then
  23.                         error( param )
  24.                     else
  25.                         tFilters[r] = param
  26.                     end
  27.                     if coroutine.status( r ) == "dead" then
  28.                         _routines[n] = nil
  29.                         living = living - 1
  30.                         if living <= _limit then
  31.                             return n
  32.                         end
  33.                     end
  34.                 end
  35.             end
  36.         end
  37.         for n=1,count do
  38.             local r = _routines[n]
  39.             if r and coroutine.status( r ) == "dead" then
  40.                 _routines[n] = nil
  41.                 living = living - 1
  42.                 if living <= _limit then
  43.                     return n
  44.                 end
  45.             end
  46.         end
  47.         eventData = { event.pull() }
  48.     end
  49. end
  50. parallelApi={
  51. waitForAny = function ( ... )
  52.     local routines = { create( ... ) }
  53.     return runUntilLimit( routines, #routines - 1 )
  54. end,
  55.  
  56. waitForAll = function( ... )
  57.     local routines = { create( ... ) }
  58.     runUntilLimit( routines, 0 )
  59. end
  60. }
  61. return parallelApi
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement