volatile keyword c++

The volatile qualifier tells the compiler to avoid certain optimizations because the object’s value can change in unexpected ways.

CPU registers are not shared between threads or CPU’s, meaning that Thread #1 would probably never know about changes Thread #2 made and vice versa.

With the volatile qualifier in use, however, the compiler should not cache variable in a CPU register and should instead fetch it from and write it to memory each time it is accessed.


volatile int x;

Thread #1:
   Write 1 to x
   Read x

Thread #2:
   Write 2 to x
   Read x

Use of volatile would only slowdown performance. Use volatile if mutex is not used.
If the variable you are using is a simple data type (i.e. int, bool) you do not need a mutex. If you do not use a mutex you must use volatile.
If the variable is complex (ie std::string, std::vector) you must use a mutex, if there is any possibility at all that the variable will be updated while another thread is trying to access it.

Don’t try to use volatile variables as a way to synchronize , it won’t work reliably.

Resolving technical problems:

Solve your technical problems instantly

We provide Remote Technical Support from Monday to Sunday, 7:00PM to 1:00 AM

Mail your problem details at writeulearn@gmail.com along with your mobile numberand we will give you a call for further details. We usually attend your problems within 60 minutes and solve it in maximum 2 days.

2 thoughts on “volatile keyword c++”

  1. Hi , How you can relate , volatile and mutex ?…mutex for mutual exclusion , while volatile will get the effect of the exteranal changes like hardware register change.

  2. Hi ,
    you are right !!
    But both are kind of synchronization techniques.
    A mutex includes a memory barrier to ensure the proper ordering of load and store operations. Adding the volatile keyword to a variable within a critical section forces the value to be loaded from memory each time it is accessed. The combination of the two synchronization techniques may be necessary in specific cases but also leads to a significant performance penalty. If the mutex alone is enough to protect the variable, omit the volatile keyword but doing it vice-versa (i.e. attaining correct ordering of accessing a variable by different threads )may not be a good idea.

    What i meant is It is also important that we do not use volatile variables in an attempt to avoid the use of mutexes. In general, mutexes and other synchronization mechanisms are a better way to protect the integrity of your data structures than volatile variables. The volatile keyword only ensures that a variable is loaded from memory rather than stored in a register. It does not ensure that the variable is accessed correctly by your code.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.