Attention | Topic was automatically imported from the old Question2Answer platform. | |
Asked By | Charlie |
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.
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.
Charlie | 2018-12-14 17:15