Is it useful to indicate variables as mutable if they are common to threads?

Note!

Obviously, I cannot clearly point out everyone here, and this is incredibly frustrating. My goal was to dispel the myth that it is volatileactually non-op, that it does nothing. I did not try to argue that it should be used, which is important so that it is not redundant, etc.

I showed that I volatilewas still doing something. I admit that under certain circumstances it is redundant and that a multi-threaded example was a bad choice.

Nor am I trying to hide the fact that my initial changes in the answer contained errors. But this Q&A does not even come close to fulfilling the intended goal. To this end, I think it is time to drop it.

Thanks to Kerrek and TC for their understanding. I just don't think that their answers correspond to the question I wanted to ask. I am sure that it was my fault that he asked poorly.

Therefore, I refuse this! And closing it as a duplicate of the question is not that it was intended, but that it was interpreted as.

Hooray! (& hth.)

I am writing to a variable in one thread and reading it in another. I was told that it is volatilecompletely useless for this, and that I do not need to use it that day and at an age if I do not work with the equipment.

int x = 0;
void thread1()
{
   while (true) {
      sleep(1);
      if (x > 0)
         break;
   }
}

void thread2()
{
   while (true) {
      sleep(1);
      x++;
   }
}

Can I get anything using volatilein this case?
What about xnot a simple intbut a class type?

+4
1

, volatile . . . , volatile.

, , , , . :

#include <atomic>

std::atomic<int> x = 0;

void thread1()
{
   while (true) {
      sleep(1);
      if (x > 0)
         break;
   }
}

void thread2()
{
   while (true) {
      sleep(1);
      x++;
   }
}

volatile.

, volatile , , , , :

// Spend some time
for (volatile int i = 0; i != LARGE_NUMBER; ++i)
{ /* do nothing */ }

// or even:
for (int i = 0; const_cast<volatile int &>(i) != LARGE_NUMBER; ++i) {}
+20

All Articles