1

I have a few questions about cache lines.

We have two variables in the same cache line, a and b.
Thread 1 reads a and thread 2 reads b.
We know that both threads read the entire cache line (they both read a and b).
But, thread 1 modifies a and thread 2 modifies b.

  1. Do both threads write the entire cache line to the main memory ?
    and if they do does it cause to other variables in the same cache line to change ?
  2. do cache lines have mutual exclusion for reading and writing ?
Solomon Slow
  • 25,130
  • 5
  • 37
  • 57
AmirCH
  • 49
  • 2
  • 1
    Give this a read: https://software.intel.com/content/www/us/en/develop/articles/avoiding-and-identifying-false-sharing-among-threads.html – NathanOliver Sep 15 '21 at 13:20
  • 1
    You didn't tag any specific hardware architecture, so there's no way to give a definitive answer. In case of [tag:x86], the cache coherency protocol will ensure the appearance of mutual exclusion, at the cost of performance. – rustyx Sep 15 '21 at 16:45
  • In x86, it is also possible to bypass the CPU cache completely, by performing [non-temporal writes](https://stackoverflow.com/q/37070/12149471). – Andreas Wenzel Sep 15 '21 at 16:49

1 Answers1

0

1 Strictly no (for variables, but not for bit fields). C/C++ standards require the implementation of reliable shared access to neighboring memory areas;

2a) On strongly-ordered systems (x86, SPARC TSO, IBM mainframe), implement coherence protocols are similar to mutual exclusion, but prohibit only simultaneous writing of two CPUs, while allowing concurrency writing and reading (in your case for different variables it is safe). See: https://en.wikipedia.org/wiki/Consistency_model#Relaxed_write_to_read ;

2b) On weak ordering systems (RISC-V, ARM, SPARC RMO) implementation of consistency protocols can be more fun. See:https://en.wikipedia.org/wiki/Consistency_model#Relaxing_read_and_read_to_write_program_orders

Serge3leo
  • 411
  • 2
  • 4