How to execute 2 threads exactly at the same time

task.spawn(function()--thread 1
print("a")
end)
task.spawn(function()--thread 2
print("b")
end)

I’m trying to the 2 thread this at exactly the same time, but it kinda delay the 2nd thread,
is there a way to execute the 2 thread at the EXACTLY same time

1 Like

TL;DR - the answer you’re looking for is “No”.

The top thread in this example will always be created first since it’s ordered on top of the other, and code is ran from top to bottom, so it will always create thread 1 first, then create thread 2. In this environment, this code still technically runs in a single hardware thread, but the Luau interpreter does a good job at handing back the execution time back and forth between the different “threads” so that it looks like they’re running simultaneously when they really aren’t, so one of them must always start first under this limitation.

The only way “around” this would be with Parallel Luau where you use hardware multithreading, but even that is never guaranteed since while the two functions can start at the “exact” same time, there’s no guarantee that they actually will due to the generally unpredictable nature of multithreading, it’s part of the reason why many things are restricted when utilizing Parallel Luau.

People might be able to offer more help if we know why you want to execute two threads simultaneously, since usually there is no reason to actually do this regardless.

3 Likes

You could try using two different scripts. Although there could be a delay between scripts too, as they can load at different times.

I guess you could make both scripts wait for something before running?

1 Like

This is actually possible using a workaround

local start = false

task.spawn(function()
	repeat task.wait() until start == true
	print('a')
end)
task.spawn(function()
	repeat task.wait() until start == true
	print('b')
end)

task.wait(5)
start = true

These 2 functions run at the exact same time (as shown in image below)
image

With some modifications, I’m sure this could probably fit to what you’re trying to accomplish

1 Like

It’s not instant though. Also I don’t see why you would need two threads to start at the exact same time anyways. I think this post should be about how to handle whatever they need simultaneous execution for.

2 Likes

It will never execute at the same exact time.

1 Like
  1. Stop bumping this post
  2. This is clearly an XY problem
5 Likes

U can make a main script and then toggle some value from it, and 2 other scripts wait for that value to be toggled and then execute whatever u want

1 Like