-
Notifications
You must be signed in to change notification settings - Fork 8
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Thread pooling for the Spawn util (#8)
* Update Spawn.luau * use last thread instead of swap popping
- Loading branch information
Showing
1 changed file
with
12 additions
and
10 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |