Skip to content

Instantly share code, notes, and snippets.

@kurapica
Created July 12, 2021 07:06
Show Gist options
  • Save kurapica/714f9f5ea5cfb686e848a6781388b0cf to your computer and use it in GitHub Desktop.
Save kurapica/714f9f5ea5cfb686e848a6781388b0cf to your computer and use it in GitHub Desktop.
Lua simple thread pool
local create = coroutine.create
local resume = coroutine.resume
local running = coroutine.running
local status = coroutine.status
local wrap = coroutine.wrap
local yield = coroutine.yield
local tinsert = table.insert
local tremove = table.remove
local PREPARE_CONFIRM = {}
local _ThreadPool = {}
local function returnwithrecycle(thread, ...)
if #_ThreadPool < 100 then tinsert(_ThreadPool, thread) end -- recyle the thread
yield(...)
end
local function preparefunc(thread, func, ...)
returnwithrecycle(thread, func(...))
end
local function recyclethread(thread)
while true do preparefunc(thread, yield(PREPARE_CONFIRM)) end
end
local function newrecyclethread()
local thread = tremove(_ThreadPool)
-- Check Re-usable
if thread then for i= 1, 3 do if thread() == PREPARE_CONFIRM then return thread end end end
-- Create the new thread
thread = wrap(recyclethread)
thread(thread) -- pass the thread to be recycled
return thread
end
function ThreadCall(func, ...)
local thread = newrecyclethread()
return thread(func, ...)
end
print(
ThreadCall(function(...) print(coroutine.running(), ...) return 1 end, 1, 2, 3)
)
print(
ThreadCall(function(...) print(coroutine.running(), ...) return 2 end, 4, 5, 6)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment