Are race conditions possible when incrementing NumberValue objects from multiple threads?

I am coding a game where the player can purchase objects that will each individually increment their money on time intervals. If the player’s money is stored in a NumberValue, and multiple of these objects are running loops in their own threads, if two of them increment the NumberValue at the exact same time, will it fail to increment, or not increment as much as it should?

So far, I have tried to cause a race condition to happen by spawning many threads that increment a NumberValue and I haven’t been able to get it to happen, which is re-assuring. But the reason I am double checking here is because race conditions are a tricky thing and sometimes they aren’t replicable across different types of hardware and operating systems.

So does anybody know for sure whether or not it’s possible that this happens, and if so, how I might avoid it?

I don’t think it is truly possible for the values to be set at the exact same time. I might be wrong, but I don’t think there is any realistic chance you’ll run into this problem. Even when code is run at the same time, I believe there is still a order in which it is processed, as is the nature of computers. Possibly some malfunction could happen that causes such a problem, but I wouldn’t worry about it unless you see it happening.

The only real way I could see this happening, is if there is noticeable delay between your one thread getting the old value, and resetting it, in which another thread sets the value. This would mean the first thread would set the value while ignoring the changes from the second, since at the time between getting its value, and editing and resetting, it hadn’t been updated by the second.

Lua threads aren’t real threads. They happen one after another and there are no race conditions. There are upcoming features that will introduce true multithreading, but it’s unrelated to this.

4 Likes

I never knew this about Lua, I looked into it because of this post. Very interesting and thanks for answering my question!

1 Like