Memory safe Thread Execution Method

Hi so, I recently noticed that people normally have a hard time cleaning up threads as well as people having a hard time getting used to the task library due to it being way faster and more performant then the coroutine library.

Like the cleanup method for coroutine library. I made a small function where it uses xpcall and creates and runs a given function as a thread, then like coroutine.yeild and coroutine.close it defers then cancels the thread.

This thread will then be unable to be referenced but It’s safe to recall the function and create a new thread.

Here is the function:

Function
type thread = RBXScriptConnection

return function(fn: RBXScriptConnection) : thread
	local t: thread
	local function rThread(...)
		xpcall(function(...)
			t = task.spawn(fn)
			task.defer(task.cancel, t)
		end, function(...)
			error(`error during thread execution`)
		end)
	end
	rThread()
end

If you’d rather clean it up yourself, thats fine but this is a safe way to also make threads and clean it up.

Also here is the module if u dont know where to write it!

ProtectedSpawn.lua (312 Bytes)

(Lua C stuff ahead)

Roblox when doing task.spawn will very much make a new lua_State, which is what represents a thread. Lua states are subject to garbage collection like any Lua object unless referenced on the Lua registry, which it probably isn’t if it is ignored and it finishes execution I believe.

Leaving all that, though, a thread is not an RBXScriptConnection, and you cannot spawn it, task.spawn and spawn take a function not a connection, that being besides the point, this will spawn it, and then after one scheduler tick kill it, it doesn’t really account to any “protected spawn”, rather just a broken function I believe, but I haven’t ran it myself, these I just believe is how it will run

1 Like

sorry that i messed up on the typing haha, I did run some test and the thread did seem to work pretty fine but if you have any more suggestions im open to improvement

The problem is, I don’t believe this solves anything honestly, task.spawn will not error if the code inside of it errors as far as I’m concerned