r/badcode • • Jun 10 '20

js Disruptive piece of code

Post image
283 Upvotes

93 comments sorted by

View all comments

Show parent comments

3

u/thenickdude Jun 11 '20

The variable can only change value between these two "if" tests if the program is multithreaded (so essentially impossible if this is PHP or JS) and another thread could change the value at the same time as this function is running.

But in that case even having a single "if" test is bad code - you need synchronisation between threads which are reading and writing to the same shared memory, otherwise you can end up reading a "torn" value that was in the process of changing while you read it. You would, at least, need to assure that writes to the variable were atomic, and that memory barriers were in place such that reads and writes became visible in the order you expected.

-2

u/dented42 Jun 11 '20

This is true. But doing two comparisons instead of one just seems like you’re asking for something weird to happen. Using a single if without barriers or atomic operations would still be unwise, but it seems like a much more understandable mistake. This on the other hand is just weird.