I'm confuse with the problem, it just come up when I review someone's C++ code.
For example in C++:
// Global var
int g_var = 0;
// thread 1 call Func1() forever:
void Func1() {
++g_var;
}
// thread 2 call Func2() forever:
void Func2() {
--g_var;
}
Define the Func1 call times times1, Func2 call times times2
- Does
times1 - times2always= g_var? - What if the code is in
Cnot inC++? - What if the
g_varusevolatiledecoration? - Does using atomic_increase/atomic_decrease is the only right way?
What I think, it should use violatile in C++, not ecessary use atomic operation like InterlockedIncrement in Windows, because the assembly code is just one line, one add instruction:
mov eax,1
add dword ptr [a],eax