How to ensure an operation/function is atomic?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By bli00

I’m not entirely sure how to go about ensuring certain operations happen atomically. That is, how to ensure that a operation happens within one frame rather than it spanning two or maybe even multiple frames?

Say I have the following callback that could be triggered at anytime:

func _on_signal_received():
    status = "ACTIVE"
    # other stuff that needs to happen to become "active"

Then assume I’m processing by checking status somewhere:

func _physics_process(_delta: float) -> void:
    if status == "ACTIVE":
        # do important stuff

How do I ensure that # do important stuff in _physics_process don’t start right after the status is set to "ACTIVE" (but before # other stuff that needs to happen to become "active")? Does the answer change if it’s _process instead of _physics_process?

:bust_in_silhouette: Reply From: godot_dev_

I am not sure if Godot 4.0.1’s thread processing differs from older versions of Godot, but assuming its similar, the signal handling functions that are called when a signal is emitted are all executed on the main thread, just like _physics_process and _process. This assumes of course you are not working with multiple threads (if you didn’t create any threads), in which case all your function calls will be atomic.

If you are doing multi-threading, you may want to consider mutex locks and semaphors to acheive what you are trying to do.

So I know the execution order of things like _init() or _ready(). Do you know where I can find detailed information about all execution orders? e.g. things like whether if _physics_process is called before or after _process, and when are signal callbacks handled.

bli00 | 2023-04-03 21:31

I am not sure where the documentation is, but you could investigate it using break points to see which break point catchs first. Signal callbacks are straight forward: they are called immediatly after a signal is emitted (Observer pattern)

godot_dev_ | 2023-04-03 22:35

Thank you very much!

bli00 | 2023-04-04 01:00