How thread safe are static fields?
-
In the following struct:
public struct myStruct { public static int CumulativeCountOfInstances; public myStruct(int SomeUnusedData) { CumulativeCountOfInstances++; } }
If concurrent processes are creating
myStruct
structs, what prevents collisions as each instance tries to incrementCumulativeCountOfInstances
? -
In the following struct:
public struct myStruct { public static int CumulativeCountOfInstances; public myStruct(int SomeUnusedData) { CumulativeCountOfInstances++; } }
If concurrent processes are creating
myStruct
structs, what prevents collisions as each instance tries to incrementCumulativeCountOfInstances
?Nothing prevents it. Maybe a good place for an interlocked increment :) How are different processes sharing the same variable? Or did you mean concurrent threads? Mark
Mark Salsbery Microsoft MVP - Visual C++ :java:
-
Nothing prevents it. Maybe a good place for an interlocked increment :) How are different processes sharing the same variable? Or did you mean concurrent threads? Mark
Mark Salsbery Microsoft MVP - Visual C++ :java:
I definitely mean concurrent threads. Friday afternoons are very hard on my concentration. So I should use Interlocked increments from my constructor, AND I should should use Interlocked exchange any time I want to read this value? Dang,
static
isn't as static as I thought it was :-) -
I definitely mean concurrent threads. Friday afternoons are very hard on my concentration. So I should use Interlocked increments from my constructor, AND I should should use Interlocked exchange any time I want to read this value? Dang,
static
isn't as static as I thought it was :-)If you use Interlocked.Increment() / Interlocked.Decrement() then the new value will be returned (an increment and a read are combined in one atomic operation). Reading (for integer types) is atomic (except for 64-bit integers on a 32-bit processor) so there's no Interlocked.Read except for longs. You could use Interlocked.Exchange() if that's what you need to do, but it's not appropriate for just reading the value (what value would you exchange?). To write/modify the variable beyond the atomic operations provided by the Interlocked class, you'll need to use some other type critical section, like lock. Mark
Mark Salsbery Microsoft MVP - Visual C++ :java:
-
If you use Interlocked.Increment() / Interlocked.Decrement() then the new value will be returned (an increment and a read are combined in one atomic operation). Reading (for integer types) is atomic (except for 64-bit integers on a 32-bit processor) so there's no Interlocked.Read except for longs. You could use Interlocked.Exchange() if that's what you need to do, but it's not appropriate for just reading the value (what value would you exchange?). To write/modify the variable beyond the atomic operations provided by the Interlocked class, you'll need to use some other type critical section, like lock. Mark
Mark Salsbery Microsoft MVP - Visual C++ :java: