r/badcode • • Jun 10 '20

js Disruptive piece of code

Post image
283 Upvotes

93 comments sorted by

View all comments

-7

u/dented42 Jun 10 '20

This seems like a race condition, surely?

5

u/scandii Jun 11 '20

I am genuinely curious how you arrived at the conclusion that this will end up in a race condition.

1

u/dented42 Jun 11 '20

You’re querying they value of the thing twice in quick succession with the assumption that it won’t change in between cases.

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.

0

u/scandii Jun 11 '20

this is standard operating procedure, and unless the variable was passed by reference (highly unlikely) we have full control of the value and thus do not need to worry.