1

I have started working to learn multicore programming. I started leaning c++11 atomics. I would like to know if all he shared variables needs to be atomic?

subbu147
  • 346
  • 1
  • 9
  • No, not all. Also there are other methods to maintain sequential consistency (the obvious one is locks). The question itself shows that you have no idea what you are asking about. To fix this, check [The Definitive C++ Book Guide and List](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and specifically [C++ Concurrency In Action by Anthony Williams](http://rads.stackoverflow.com/amzn/click/1933988770). Make some more research on topic before asking anything else. – Ivan Aksamentov - Drop Oct 08 '15 at 07:58

3 Answers3

0

If multiple thread accessing (read/write) the same variable then it should be atomic. Also you can go though this.

Community
  • 1
  • 1
Mohan
  • 1,871
  • 21
  • 34
  • If multiple threads read the same variable there is no point to make it atomic. – Ivan Aksamentov - Drop Oct 08 '15 at 07:57
  • @Drop if only reading then may not required but in read/write case it is required this what I learned from this http://stackoverflow.com/questions/31555700/do-i-really-need-mutex-lock-in-this-case – Mohan Oct 08 '15 at 08:06
0

The only time a variable needs to be "atomic", i.e., can be updated in "one fell swoop, without any other thread being able to read it meanwhile", is if it even can be read while someone else is updating it. For instance, if it's set on initialization and then never changes, no one can ever read it while it's changing, and so it doesn't have to be atomic. On the other hand, if it ever changes after initialization and there's a risk that anyone else than the changing thread reads it while it's changing, then it needs to be atomic (atomic intrinsics or protected by mutex or otherwise)

Johann Gerell
  • 24,991
  • 10
  • 72
  • 122
0

Not necessarily for all scenarios. Also, note that atomicity of variable access alone does not guarantee full thread safety. It just ensures that the particular variable being read is got as a whole.In some architectures, the read operation does not happen in single assembly instruction. For example, if you are reading 64 bit value, the compiler might implement the read using two load instructions of assembly such that the 1st instruction reads the lower 32 bits and the 2nd instruction reads the higher 32 bits. This in turn can lead to race condition. So, atomic reads are preferred.

Karthik Balaguru
  • 7,424
  • 7
  • 48
  • 65