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 ?

KodeWarrior
  • 3,538
  • 3
  • 26
  • 40

1 Answers1

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%.

Yury Schkatula
  • 5,291
  • 2
  • 18
  • 42