4 ms·
Neither of those optimizations looks safe to me. Couldn't they potentially introduce deadlocks?
by endoplasm 9y ago
Neither of those optimizations looks safe to me. Couldn't they potentially introduce deadlocks?
- adrianmonk 9y agoI had the same reaction, but now I'm starting to suspect it actually is safe, for a reason that's not immediately obvious. Consider the unoptimized version. It's possible that after you release the lock, another thread will take it. But I'm pretty confident there is no guarantee of this, and your own thread might immediately take the lock back. (Probably often, especially if there's just one CPU.) If taking the lock back immediately causes a deadlock, then your code is already broken as written. So you already must account for the possibility that nothing changes between the time you release the lock and take it again. All the optimization does is take away the _other_ possibility, which was something you couldn't rely on anyway.
- endoplasm 9y agoYes, you're right. The definition of an optimization being ``safe'' is tricky in the presence of non-determinism. The set of possible executions of a correctly optimized program should be a subset of---and specifically, need not be necessarily equal to---the possible executions of the original unoptimized version.