Multithreading
By default, code is singlethreaded: instructions run one by one. However, there are two ways to achieve multithreading, where multiple pieces of code run side-by-side.
Multithreading with thread
thread
The thread
directive will execute everything in it parallel to other code. This works functionally the same as creating a new block in Visual Scripting, and not connecting any other block to it (so it's executed as soon as the script is ran).
An example of thread
usage is:
Without the thread
directive, first the 10 second wait would have to finish, and only then the 5 second wait would start. With the thread
directive, both the 10 second and 5 second waits start at the same time, therefore the 5 second wait will finish earlier.
Because of how thread
works, code attached to it will run before all other code, even if it's not on the first line. Therefore you must be careful with it.
Multithreading with Events
It is possible to use BindableEvents to multithread. This involves simply creating a new BindableEvent using Instance.new
, then connecting to its event
and :Fire()
ing it. The code attached to event
will run in parallel to other code after it is fired. Read Events to understand this more.
Last updated