Skip to content

Commit

Permalink
Thread pooling for the Spawn util (#8)
Browse files Browse the repository at this point in the history
* Update Spawn.luau

* use last thread instead of swap popping
  • Loading branch information
Aspecky authored Jan 13, 2024
1 parent 60afc82 commit 3ede2cd
Showing 1 changed file with 12 additions and 10 deletions.
22 changes: 12 additions & 10 deletions libs/Spawn/Spawn.luau
Original file line number Diff line number Diff line change
@@ -1,23 +1,25 @@
local FreeThread: thread? = nil
local FreeThreads: { thread } = {}

local function FunctionPasser(Callback, ...)
local AquiredThread = FreeThread
FreeThread = nil
local function RunCallback(Callback, Thread, ...)
Callback(...)
FreeThread = AquiredThread
table.insert(FreeThreads, Thread)
end

local function Yielder()
while true do
FunctionPasser(coroutine.yield())
RunCallback(coroutine.yield())
end
end

return function<T...>(Callback: (T...) -> (), ...: T...)
if not FreeThread then
FreeThread = coroutine.create(Yielder)
coroutine.resume(FreeThread :: any)
local Thread
if #FreeThreads > 0 then
Thread = FreeThreads[#FreeThreads]
FreeThreads[#FreeThreads] = nil
else
Thread = coroutine.create(Yielder)
coroutine.resume(Thread)
end

task.spawn(FreeThread :: thread, Callback, ...)
task.spawn(Thread, Callback, Thread, ...)
end

0 comments on commit 3ede2cd

Please sign in to comment.