0 votes

I've read the "Thread safe APIs" document and it states that I can safely read or write to variables or array or dict elements. However, I'm wondering if GDScript statements like "x += 1" are guaranteed to reflect the operations of multiple threads. I think this is an implementation question. If it is really...

x = x + 1

...then I could imagine two threads (almost simultaneously) reading x, seeing the same value, and then writing the same incremented value to x. Thus we have incremented +1 instead of +2 as I would hope. (And would the answer be the same for similar operations on non-int types -- in particular, float?)

I'm sure this is a very basic question for experts. But that's the level I'm working at.

Edit: links to source code are more than welcome. I can somewhat read & understand C++, but am too ignorant to know where to look most of the time.

in Engine by (105 points)
edited by

OK, googling a bit makes me fairly certain that this is NOT safe. Some python bytecode for "x += 1" from 2013:

  3           0 LOAD_GLOBAL              0 (x)
              3 LOAD_CONST               1 (1)
              6 INPLACE_ADD         
              7 STORE_GLOBAL             0 (x)
             10 LOAD_CONST               0 (None)
             13 RETURN_VALUE

So "x += 1" is really "x = x + 1" and it is very possible that increment from two threads will result in only one increment. If someone knows, please tell us if this is different in GDScript.

Please log in or register to answer this question.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.