Is volatile bool for thread control considered wrong?

You don’t need a synchronized variable, but rather an atomic variable. Luckily, you can just use std::atomic<bool>.

The key issue is that if more than one thread accesses the same memory simultaneously, then unless the access is atomic, your entire program ceases to be in a well-defined state. Perhaps you’re lucky with a bool, which is possibly getting updated atomically in any case, but the only way to be offensively certain that you’re doing it right is to use atomic variables.

“Seeing codebases you work in” is probably not a very good measure when it comes to learning concurrent programming. Concurrent programming is fiendishly difficult and very few people understand it fully, and I’m willing to bet that the vast majority of homebrew code (i.e. not using dedicated concurrent libraries throughout) is incorrect in some way. The problem is that those errors may be extremely hard to observe or reproduce, so you might never know.

Edit: You aren’t saying in your question how the bool is getting updated, so I am assuming the worst. If you wrap your entire update operation in a global lock, for instance, then of course there’s no concurrent memory access.

Leave a Comment

tech