Is this code thread safe?

This is a simplified version of some code that I currently support:

int SomeFunc() 
{
  const long lIndex = m_lCurrentIndex;
  int nSum = 0;
  nSum += m_someArray[lIndex];
  nSum += m_someArray[lIndex];
  return nSum;
}

lCurrentIndex is periodically updated by another thread. The question is; will create a local copy of m_CurrentIndex, make sure that both calls to m_someArray use the same index?

Note that this is a simplified example; I’m thinking about the concept of creating a local copy, and not about which code is shown here. I know that the compiler will put this value in a register, but it is still a local copy, and not reading from lCurrentIndex twice.

Thanks!

Edit: the initial assignment is safe, both guarantees are guaranteed to be 32 bits in our setup. Edit2: And they are correctly aligned on the 32-bit border (forgot about it)

+3
7

, , , . (, , 8- ). , - , / , .

+15

m_CurrentIndex , to m_someArray ?

SomeFunc, , . (lIndex) .

, : m_someArray[lIndex] ( lIndex) ; m_ someArray ; lIndex.

+6

, , . , "". . , .

+3

( , / , ). , , m_lCurrentIndex volatile. , .

+3

, , - m_lCurrentIndex lIndex ? , , , , .:)

: , .

+1

, , .

, . , " " m_lCurrentIndex lIndex .

x86 , m_lCurrentIndex DWORD , long DWORD ( x86), , . , x64 , long DWORD m_lCurrentIndex, DWORD long 64b, m_lCurrentIndex 64b, , . .

, CAS ( , , , , , ), , , .

Memory barries

: , , , , . , , . .

+1

, . , m_lCurrentIndex . , , m_lCurrentIndex, . , , , lIndex. , m_lCurrentIndex lIndex .

0

Source: https://habr.com/ru/post/1713736/


All Articles