Add a Task Function for Yielding until a Thread is Dead

Sometimes there arises cases where a thread needs to spawn another thread and then yield itself until the thread is finished.

The main case for this is spawning multiple separate-running threads while yielding the main thread until each one has finished, such as with modular frameworks utilizing game:BindOnClose.

The Proposal

Add a spawner function to the task library (i.e. task.yield) that takes in a thread or function and its arguments and yields the outside thread that called it until the spawned thread’s state becomes "dead".

This way, we can implement the above multi-spawning mechanism:

local function Execute(Running: thread, Thread: thread, Arguments: {thread}, Index: number)
	task.yield(Thread)
	table.remove(Arguments, Index)
	
	if #Arguments == 0 then
		task.spawn(Running)
	end
end

local function AwaitAllThreads(...: thread)
	local Running = coroutine.running()
	local Arguments = {...}
	
	for Index, Thread in next, Arguments do
		task.spawn(Execute, Running, Thread, Arguments, Index)
	end
	
	coroutine.yield()
end
2 Likes