Is increment an atomic operation in JavaScript? If one thread is accessing
++i; and at the same time another one starts to access the operation will there be any problems?
- 125,859
- 15
- 164
- 254
-
there is no thread in JS. – n00dl3 Mar 30 '17 at 11:05
-
JavaScript does not have threads. It does have workers (if you are in the right environment) (https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers) that can pass communications trough a message bus. – Jon Koops Mar 30 '17 at 11:06
4 Answers
in Javascript always a function runs to completions that means if a function is running than it will run completely , only after that the other function will be called so , there is no chance of interleaving between statements( but in case of java it is different ) ,if you are confused with asynchronous execution than always remember async means later not parallel , So, coming to your problem, the answer is ,No you will not face any problem, it will be total atomic operation.
- 1,667
- 11
- 29
Javascript is single threaded, So you need to worry about deallocks or dirty read problems. Why doesn't JavaScript support multithreading?
-
What about generator functions ? Surely you can exit a generator function before it have ended! – Hivaga Jun 21 '19 at 16:16
Javascript does not support multithreading. It may have web workers, but your question would not apply to this case, as workers do not share variables.
Yes there will be a problem. Even if Javascript is single threaded, i++ is (writer + modify + write) 3 steps operation, So when anyone is taking the i variable, the other one can set the modified i to the variable area. In order to solve this issue, you can use atomic variables instead of regular variable.
- 95
- 1
- 8
-
JavaScript is single threaded, so how can any code "take" the variable `i` at the same time than other code is modifying it ? You need threads to access the same variable at the same time. – ingham Feb 08 '22 at 13:22
-
I'm not talking about the client side. In node.js, can you modify the global properties safely without using atomic variables? – Erdal76t Feb 09 '22 at 14:17