Skip to content

Instantly share code, notes, and snippets.

@lucasmz-dev
Last active September 12, 2021 02:50
Show Gist options
  • Save lucasmz-dev/bbaa0a11681a1125cc39f822c71c5539 to your computer and use it in GitHub Desktop.
Save lucasmz-dev/bbaa0a11681a1125cc39f822c71c5539 to your computer and use it in GitHub Desktop.
RecycledDefer
-- RecycledDefer is a *PROOF OF CONCEPT*.
-- It should not be used if you wanna spawn threads quickly, AFAIK that's what recycling thread with task.spawn is usually about,
-- this takes a lot longer because of table look ups, and other things.
-- So please, don't use it in an actual production.
--[[
RecycledDefer:
Library which recycles threads but with .defer, instead of using .spawn, like it usually is done.
It is a self-contained library supposed to test what I was testing out with FastSignal,
but for some reason couldn't.
]]
local RecycledThreads = setmetatable({}, {__mode = 'v'})
local function RunFunction(_function, ...)
_function(...)
end
local function RunFunctionInFreeThread(...)
local thread = coroutine.running()
RunFunction(...)
while true do
table.insert(RecycledThreads, thread)
RunFunction(coroutine.yield())
end
end
return function(_function, ...)
local _type = typeof(_function)
if _type == 'function' then
local thread = nil
local index, recyledThread = next(RecycledThreads)
if recyledThread then
RecycledThreads[index] = nil
thread = recyledThread
else
thread = coroutine.create(RunFunctionInFreeThread)
end
task.defer(thread, _function, ...)
elseif _type == 'thread' then
task.defer(_function, ...)
else
error('Invalid type for defer', 2)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment