4

Lets say we have an array of two element which are type of some primitive value.

volatile int[] a = new int[2]{0,0};

I have two threads, each of them writes/reads one of the elements. First thread works only with a[0] and second thread works only with a[1].

Can array be worked this way, or array is still required to be locked, even if different index values are being affected?

Scavs
  • 673
  • 1
  • 5
  • 16
  • 1
    This should help - https://stackoverflow.com/questions/1460634/are-c-sharp-arrays-thread-safe – kiziu Jun 20 '17 at 23:44

1 Answers1

5

A thread does not need to issue a lock on a memory location that is not used by any other thread. So in your case, a lock statement would be unnecessary.

That being said, there is a CPU cache lock you should worry about. If a[0] and a[1] both fall within the same 64-byte block, they will share a cache line, meaning that each CPU core will try to load that block of memory into onboard cache, locking out any other CPU cores. If this happens, only one of your threads can access those variables at a time, and any other threads will block until the cache is pushed back to main memory and the lock is released. This problem, known as false sharing, will throttle your performance, making a multi-threaded approach perform no better, and possibly worse, than a single-threaded solution. There is no way to turn off this lock, although you could avoid it by spacing your variables out in memory so they fall within different 64-byte blocks.

(64-byte is based on modern Wintel... your experience may vary)

John Wu
  • 50,556
  • 8
  • 44
  • 80