Can signals be used safely in multithreaded code?

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

I want to emit and respond to a signal on a non-main thread. This particular signal and target method will never be used on the main thread. Is this OK?

Related question, different scenario:
If I set flags = CONNECT_DEFERRED, then it seems clear that the target method will be called later on the main thread. Good. But is it OK if the signal was emitted from a non-main thread?

:bust_in_silhouette: Reply From: godot_dev_

I am not 100 % sure, but I think using signals with multiple threads you will need some form of synchronization mechanism (not thread safe) if your signal is handling involves a critical part of code. So if your signal handling does not affect anything related to the main thread, it’s fine. Otherwise, if your signal handling is managing a resource that the main-thread also shares, you will need some form of syncrhonization.

FYI: I use call_deferred("emit_signal","signalName") when I need the main-thread to handle a signal emitted by a thread

Yeah, that would be the case in any regular method call. I should have said there was no interaction with SceneTree or dangerous sharing with other threads. I’ll try it and post if I run into problems.

I was kind of wondering if call_deferred("emit_signal","signalName") is exactly equivalent to emitting a signal that was connected with flags = CONNECT_DEFERRED (other than possibly code readability).

Charlie | 2022-08-08 19:41

I am not sure about flags = CONNECT_DEFERRED, I haven’t looked into that.

If your signal processing won’t touch critical code shared with other threads I am fairly confident you can just use signals as usual within the threads

godot_dev_ | 2022-08-08 20:36

Thank you for the response! I’ll upvote when I am convinced from testing that this is correct. Or a dev or serious C++ code diver confirms.

Charlie | 2022-08-09 17:24