lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hi,

I thought people might be interested in this simple code below. It uses Lua coroutines support to implement similar functionality to Io's @ symbol.

It's not been thoroughly tested, but you essentially start your main loop using the start() function. Then when you want to perform a function in the background, you call it via the async() function, passing the function in as the first parameter, and the arguments in subsequent parameters. It will then return a promise, which when called with no arguments will return the result of the function, blocking if the result is not available yet.

It's not tested properly yet, so my naieve use of the threads table will probably explode - feel free to fix it.

Code follows:

threads = {}
setmetatable(threads, {__mode = "v"})

function start(fn, ...)
   local index
   local promise = async(fn, ...)
   while (#threads ~= 0) do
      for index, promise in ipairs(threads) do
         if (promise.fulfilled == nil) then
            coroutine.resume(promise.co)
         end
      end
   end
end

function async(fn, ...)
   local arg = {...}
   local index = #threads + 1
   local promise = {}
promise.co = coroutine.create(function() promise.fulfilled = fn(unpack(arg)) threads[index] = nil end)
   setmetatable(promise, {
      __call = function ()
         while (promise.fulfilled == nil) do
            coroutine.yield()
         end
         return promise.fulfilled
      end
   })
   threads[index] = promise
   return promise
end

function a(x, y)
   return x+y
end

function b()
   local a1=async(a, 1, 2)
   local a2=async(a, 3, 4)
   print(a2())
   print(a1())
end

--
Lisa