1

I have the following class

class Thread
{
   int m_state;
   Mutex m;
   CondVar v;

   Thread(): m_state( 0 ) {}

   write()
   {
     // Get mutex m
     // m_state = 1;
     // signal v
   };

   read()
   {
      // Get mutex m
      while( m_state == 0 )
      {
         wait v;
      };
   };
};

read() and write() can be called on separate threads.

In this case, do we have to make m_state or volatile or the compiler ensures that optimizations ( such as reading m_state from memory to register and spinning on register ) is prevented ?

2
  • It is safe against optimizations.
    – nwp
    Aug 3, 2015 at 11:58
  • It is not the meaning of volatile.
    – Jarod42
    Aug 3, 2015 at 11:59

1 Answer 1

0

Volatile will not help here as there is two-fold issue:

  1. compiler optimizing reads/writes (can be managed by compiler, partially)
  2. internal CPU instructions reordering (can't be managed by compiler)

So you have to mark the shared variable at least with memory barriers, to prevent the reordering. Mutex will fit here (not the most performance but it will work). Also, you can try any available reader-writer locks as it should fit your semantics 100%.

Not the answer you're looking for? Browse other questions tagged or ask your own question.