Use volatile variable in multi-thread programming

About volatile variable, I think 4.3.4.2 A Volatile Solution from Is Parallel Programming Hard, And, If So, What Can You Do About It? is a good reference. The following is excerpted from it:

To summarize, the volatile keyword can prevent load tearing and store tearing in cases where the loads and stores are machine-sized and properly aligned. It can also prevent load fusing, store fusing, invented loads, and invented stores. However, although it does prevent the compiler from reordering volatile accesses with each other, it does nothing to prevent the CPU from reordering these accesses. Furthermore, it does nothing to prevent either compiler or CPU from reordering non-volatile accesses with each other or with volatile accesses. Preventing these types of reordering requires the techniques described in the next section.

So if your variables satisfies following conditions:

(1) The load and store of variable is machine-sized and properly aligned;
(2) Code reordering doesn’t affect the logic of program.

You can use volatile.

BTW, there is a code sample for reference.