Grieve (grieve) wrote,
Grieve
grieve

Volatile does not thread safe make.

I keep running across code, some old and some new, that uses the volatile keyword in an attempt to make the code thread "safe". Using that is always suspect, and without a truly deep understanding of the underlying hardware I doubt you could ever prove it was safe. With todays modern dual core processors, you can be 100% certain that it is unsafe.

In a nutshell volatile means to fetch the value from memory, and ignore whatever may be in the cache. What does that mean when you have two caches? At any rate when I see these items in the code I remove them. What is doubly irritating about them is that I tend to see them in java. Where classes like AtomicInt and AtomicBoolean are part of the libraries.
Tags: programming, thread safety
Subscribe

  • A C++ quiz

    Suppose I gave you the following snippets of code: #include <cstdio> void Class::PrintFoo() { printf("Foo\n"); } int main() { Class13 c13;…

  • How many Univacs is that?

    Today at work one of my coworkers had a new phone. I flippantly asked him how many Univacs it was? Of course in a room full of geeks once a question…

  • Live Journal Styles

    So Live Journal was complaining that the underlying style mechanism (S1) I was using was going to go away, and I should switch to the new mechanism…

  • Post a new comment

    Error

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.
  • 2 comments