Skip to content

Instantly share code, notes, and snippets.

@Quenty
Created December 15, 2020 03:14
Show Gist options
  • Save Quenty/ca8f84c4b35dd2738b101e00d9ab1d98 to your computer and use it in GitHub Desktop.
Save Quenty/ca8f84c4b35dd2738b101e00d9ab1d98 to your computer and use it in GitHub Desktop.
local BINDABLE_FUNCTION_NAME = "BindableFunctionForTaskFarm"
local function setupTaskFarm(tasks)
local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore"))
local Promise = require("Promise")
local RandomUtils = require("RandomUtils")
local PromiseUtils = require("PromiseUtils")
local functions = {}
for i=1, tasks do
local actor = Instance.new("Actor")
actor.Name = "Actor_" .. i
local bindableFunction = Instance.new("BindableFunction")
bindableFunction.Name = BINDABLE_FUNCTION_NAME
bindableFunction.Parent = actor
table.insert(functions, bindableFunction)
script:Clone().Parent = actor
actor.Parent = script.Parent
end
return function(args)
local promises = {}
for i=1, #args do
table.insert(promises, Promise.spawn(function(resolve, reject)
-- It's not as bad as you might think to randomly schedule
-- tasks like this
local bindableFunction = RandomUtils.choice(functions)
local results
local ok, err = pcall(function()
results = {bindableFunction:Invoke(unpack(args[i]))}
end)
if not ok then
return reject(err)
end
if not results then
return reject("Failed to get results")
end
return resolve(unpack(results))
end))
end
return PromiseUtils.all(promises)
end
end
local function setupTaskActor(func)
local bindableFunction = script.Parent:WaitForChild(BINDABLE_FUNCTION_NAME)
bindableFunction.OnInvoke = function(...)
task.desynchronize()
local results = {func(...)}
--task.synchronize()
return unpack(results)
end
end
if not script.Parent:IsA("Actor") then
local promiseParallel = setupTaskFarm(25)
-- Let server stabilize:
wait(1)
local startTime = os.clock()
-- test paralle
local args = {}
for i=1, 100 do
table.insert(args, {i, startTime})
end
promiseParallel(args):Then(function()
print("Done executing all tasks", os.clock() - startTime)
end)
else
setupTaskActor(function(times, startTime)
print(("Executing on %s with %d after %f secs")
:format(script.Parent.Name, times, os.clock() - startTime))
end)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment