ActorPool - Makes working with Parallel Lua easier!

So Roblox recently introduced Parallel Lua so I decided to make a pooling module to make interacting with multiple Actors much easier.

How Does It Work?

It creates a table of actors that are all derived from the same base actor. You can then take an actor from the pool as needed, then put it back. This is useful for running the same functions at the same time in parallel. A use case for this module may be for a terrain generation system.


Example


Structure
image


game.ServerScriptService.Main.lua

local ActorPool = require(game:GetService("ReplicatedStorage").ActorPool)
local baseActor = script.Actor

local actors = ActorPool.New(baseActor, script.Actors, 12)

while true do
	local actor = actors:Take()
	actor:SetAttribute("doingTask", true)
	task.wait(.125)
end


game.ServerScriptService.Main.Actor.Script.lua

local actor = script.Parent
local doingTaskSignal = actor:GetAttributeChangedSignal("doingTask")

doingTaskSignal:ConnectParallel(function()
	-- makes sure that the actor only runs when "doingTask" is enabled
	if actor:GetAttribute("doingTask") == false then return end
	
	print("starting work - "..actor.Name)
	
	debug.profilebegin("An Actor Thread")
	local a,b = 0,1
	for count = 1,1000000 do a,b = b,a end
	debug.profileend()
	
	task.wait(3)
	task.desynchronize() -- desyncs the thread as "task.wait" synchronised it
	print("stopping work - "..actor.Name)
	
	-- puts the actor back into the pool
	task.synchronize()
	actor:SetAttribute("doingTask", false)
end)


Alternatively you can download the example here


API

ActorPool.New(BaseActor: Actor, Folder: Instance, Amount: Number)

This creates a new pool derived from the BaseActor. It parents all of the created actors to a pre-created Folder defined by the user. The Amount is how many actors the pool should start off with, if the pool runs out of actors then it will create new ones accordingly.


ActorPool:Take()

It takes an actor out of the pool. To start running the code within the Actor you need to set the “doingTask” attribute of the Actor to true.


The boilerplate code for the Base Actor

local actor = script.Parent
local doingTaskSignal = actor:GetAttributeChangedSignal("doingTask")

doingTaskSignal:ConnectParallel(function()
	-- makes sure that the actor only runs when "doingTask" is enabled
	if actor:GetAttribute("doingTask") == false then return end
	
	-- your code here
	
	-- puts the actor back into the pool
	task.synchronize()
	actor:SetAttribute("doingTask", false)
end)

Download It From These Places

Github Repo: ActorPool/ActorPool_V1.lua at main · MightyPart/ActorPool · GitHub
Roblox Library: ActorPool - Roblox

13 Likes

version 3 is released.

1 Like