How to add values from different threads to the same array safely?

How can I add values from threads A and B to a table from a module?

Why?

lets say A and B are simultaneously adding a value to the same index at the end of a table using table.insert, will A or B override the other, or does this never happen?

If A or B overrides the other, how do I solve this?
If not, then please explain.

1 Like

Right now, Roblox doesn’t really have parallel computing yet. It uses context switching to run multiple threads concurrently, so on the machine level operations are still being done one at a time. If both threads try to append an item to the end of the table, whichever operation happened last would get the last table position, and it might be hard to predict the order. If A needs to appear in the table before B, then you could probably sort the table when both threads finish to make sure of it. Or, if the items have to go into specific positions that you know, you could just set the indices directly when you call table.insert.

2 Likes

Thank you so much for preventing me from a headache! :slight_smile:

Yeah, as long as you don’t wait / wait on an Event, call a yielding function or yield in any way,
your operations are essentially atomic, and unlikely to be problematic.
If you’re interested in the “yet” that @blokav mentioned,

1 Like