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.

asked Dec 13, 2018 in Engine by Charlie (89 points)
edited Dec 14, 2018 by Charlie

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.