0

Let us image this situation : two threads A and B , value i is volatile , A and B execute i++.As we all know ,the process is not safe. But I do not understand why. I know that volatile has semantics for memory visibility. I also know i++ actually has three steps:

1.load i from main memory to cache 2.cpu calculate i++ 3.store i from cache to main memory.

If we do not use volatile, there will be an obvious problem. Thread A execute step one and two, then Thread B come in and execute all steps. But A do not know that. A execute step 3 and it will cover B's result. So i++ is not safe.

But if we use volatile, under above circumstance, when Thread B load its answer from cache to main memory. Thread A will know immediately, and due to MESI its cache line is invalid. So Thread A has to get the latest data from main memory to its cache and redo its job ,which means executing from step one to step three all over again. In conclusion, volatile can ensure threads always get the latest data, and those threads know what each other had done.

So why volatile can not keep i++ safe?

Dave Newton
  • 156,572
  • 25
  • 250
  • 300
tomatomaze
  • 36
  • 2
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/235394/discussion-on-question-by-tomatomaze-why-volatile-and-i-is-not-thread-safe). – Machavity Jul 28 '21 at 16:08

0 Answers0