Home > Net >  Is volatile necessary for the resource used in a critical section?
Is volatile necessary for the resource used in a critical section?

Time:07-17

I am curious about whether volatile is necessary for the resources used in a critical section. Consider I have two threads executed on two CPUs and they are competing on a shared resource. I know I need to a locking mechanism to make sure only one thread is performing operations on that shared resource. Below is the pseudo code that will be executed on those two threads.

take_lock();

// Read shared resource.
read_shared_resouce();

// Write something to shared resource.
write_shared_resource();

release_lock();

I am wondering if I need to make that shared resource volatile to make sure that when one thread is reading shared resource, a thread won't just get the value from registers, it will actually read from that shared resource. Or maybe I should use a accessor functions to make the access to that shared resource volatile with some memory barrier operations instead of make that shared resource volatile?

Thank you~

CodePudding user response:

The answer is no; volatile is not necessary (assuming the critical-section functions you are using were implemented correctly, and you are using them correctly, of course). Any proper critical-section API's implementation will include the memory-barriers necessary to handle flushing registers, etc, and therefore avoid the need for the volatile keyword.

CodePudding user response:

"if I need to make that shared resource volatile"

If an object may change due to something other than CPU1, CPU1 needs to seen the object as volatile.

In critical section or not is not relevant.

  • Related