Ive encountered a fundamental misunderstanding of Parallel Lua, can anyone clear this up?

I thought I understood Parallel Lua after reading the entire Docs and having experience in JavaScript multithreading, but I’m encountering unexpected behavior. If I make a blank project then put two Actors in ServerScriptService and put a Script under each Actor and then put this identical code in each Script:

while true do
	task.wait()
	for i = 0, 999999 do
		math.random(0,1)
	end
end

I get 50ms frametime and both scripts are executing serially, as expected. But then if I change just one of the script’s code to this:

while true do
	task.wait()
	task.desynchronize()
	for i = 0, 999999 do
		math.random(0,1)
	end
	task.synchronize()
end

and run it again, I still get 50ms frametime and they’re executing serially. I did not expect this. I expected they should now execute in parallel since I’ve told one of the scripts to leave the main thread. But if I change BOTH scripts to:

while true do
	task.wait()
	task.desynchronize()
	for i = 0, 999999 do
		math.random(0,1)
	end
	task.synchronize()
end

now I have 25ms frametime and they’re executing parallel. But I don’t get why it’s not working when I desynchronize just one script? What am I misunderstanding about how Parallel Lua works internally? This doesn’t line up with what I thought I read in the Docs.

1 Like

i think you should swap the task.synchronize and task.desynchronize

I may be completely wrong here as my understanding isn’t the best, but I believe the game executes serial code, then it executes parallel code. If one is serial and one is parallel then they will execute one after the other, which is the same as serial so there is no performance gain. If both are parallel they are able to execute at the same time so you can do it twice as fast.

2 Likes

Something about that sounds right. But when I go into the Micro Profiler while having one script that doesn’t call task.desynchronize and one script that does, not only are they running serially, but they’re shown running on the same thread, meaning the one that calls task.desynchronize doesn’t even switch to a different thread than the other code. I don’t know if that means anything. Having trouble internalizing this new information so fast.

@stuart2202 is right there are separate serial and parallel execution phases (it does mention this in the docs but isn’t obvious)

If there is only one thread designated to run in the parallel execution phase, it may not need to start a second thread, try setting both to desynchronise.

1 Like

I’ve now tested you are exactly right. Thanks so much. Everything about Parallel Lua seems to make sense now.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.