Efficient Parallel Luau Thread Handler Solution for Modules [Open Source]

This resource is for hose seeking a solution to make their required modules run in parallel using a thread handler. and a Bindable Function which transmits data.

function SetupThreads(Dungeon)
	local threads={[1]={Dungeon=script.Parent.Parent.GeneratorThreads.Generator.Generate,Busy=0}}

	local numberthreads=3
	local RunService = game:GetService("RunService")
	if RunService:IsStudio()  then
		numberthreads=1
		print("Running in Studio Character Generator using 1 Main Thread")
	else 
		for i=2, numberthreads do 	
			local DungeonThread=Dungeon:Clone()
			DungeonThread.Parent=Dungeon.Parent
			threads[i]={Dungeon=DungeonThread.Generate,Busy=0}	
		end
	end
	print("Character Generator has Setup "..tostring(numberthreads).." Parralel threads")
	return threads	
end

local Threads=SetupThreads(script.Parent.Parent.GeneratorThreads.Generator)

local function GetThread()--return dungeon and thread index to toggle busy
	local minimum=0--find minimum 
	repeat 
		for i,v in Threads do 
			if v.Busy<=minimum then
				Threads[i].Busy+=1--directly write to table
				return v.Dungeon,i
			end
		end
		minimum+=1
	until minimum>=math.huge--shouldn't ever reach this value. Over 400 instances
end

local bindableFunction = game.ReplicatedStorage.GlobalSpells.Generate-- Find the same BindableFunction object in the Workspace
bindableFunction.OnInvoke = function(name,args) -- Define a function that runs when the BindableFunction is invoked and receives the name as a parameter
	if name=="Gettable"	then--optimization
	return Threads[1].Dungeon:Invoke(name,args)
	else 
	return GetThread():Invoke(name,args)--,(args[1],args[2],args[3],args[4],args[5],args[6],args[7],args[8])
	end
end

This is a .RBXL file that demonstrates it implemented. This is something I’ve been using frequently for optimization to reduce the size of the LuaHeap by reducing the redundancy of requiring an important module. To convert simply change the module reference in the code.
It looks something like this

local dfg=require(game.ReplicatedStorage.GlobalSpells)
local bindableFunction = script.Parent.Generate-- Find the same BindableFunction object in the Workspace
bindableFunction.OnInvoke = function(name,args) -- Define a function that runs when the BindableFunction is invoked and receives the name as a parameter
return dfg[name](args[1],args[2],args[3],args[4],args[5],args[6],args[7],args[8])
end

With this instead of calling dfgfunctionname
you would write dfg:Invoke(“functionname”,{variable1,variable2})
If you find good use for this method, Let me know what you think! Originally I came up with this as an elegant solution to making this Procedural World Generator be more Parallel to increase its speed and performance.
LuauThreadHandler.rbxm (3.3 KB)

1 Like