Question about race condition w/ RemoteEvent

Hi!

I’m implementing a system in my game that relies a RemoteEvent which manipulates a global resource. I need the effects of the event to be consistent, no matter when or from whom the remote is fired.

Essentially, whenever the RemoteEvent’s OnServerEvent is called, its handler will, without yielding:

  1. Modify the global resource
  2. Do something with it
  3. Restore the global resource to its original state; end of execution

The behavior I am hoping for, is that each call of the remote event will do all of these operations at once before any other calls of the event have a chance to begin execution…

My fear, though, is that events start new threads, right? So, if two or more event calls happen at the same time, maybe it’s possible for one of these threads to begin or resume execution while the resource is already being manipulated? Therefore creating a race condition?

I want to know if this fear is warranted, and what I can do to get around it. (Cloning the shared resource is not an option)

1 Like

From doing some testing, you should be fine.

Even when doing 1000 calls immediately after each other (also tested 5 groups of 200), I was unable to get a race condition to occur.

Find attached the test place I used:
Helloburp_1.rbxl (56.0 KB)


If you still want to get around it, on the extremely extremely small chance that it happens, you can implement a queue system into the remote event, where you add the calls into a table which is gradually processed, handling one call at a time.

3 Likes

To add onto what @SeargentAUS said, if you are 100% certain the handler will not yield, you can skip the queue system altogether. Lua uses non-preemptive multithreading which means once a coroutine or “thread” starts, no other coroutine will run until the former yields or completes.

So in your case, if an event arrives while the handler is running, it’s okay because the new event must wait until the current handler has yielded or completed.

1 Like

Got it–

Thanks to you and @SeargentAUS for your help; I’ll close this thread and tag a solution!

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