Common Language Runtime
Threading question about different types...
Question:
I'm in the process of developing a multithreaded application and I started wondering about assigning values to variables. Basically I have a thread running a loop
while(!closing)
{
... do work ...
}
Where closing is a global boolean variable. I also have another sub that would always be called by an entirely different thread which has the line:
closing = false;
The loop in question is just checking for incoming socket connections so even if there's a context switch while assigning the variable I'm not too concerned if it loops a couple extra times. I'm just wondering if there's any other bad things that can happen by not using the Interlock class for this kind of thing. If not, are there any other basic types that might? char, int, long, double?
Answer1:
Hi,
Even if you are ok with possible few extra loops, I still suggest you to use lock statement during assignment operation or mark closing field as volatile.
Vitaliy Liptchinsky. Always open for interesting job offers.
Answer2:
Vitaliy Liptchinsky wrote: |
|
Hi,
Even if you are ok with possible few extra loops, I still suggest you to use lock statement during assignment operation or mark closing field as volatile. | |
I do have it defined as volatile. As I understand it that forces the compiler to load the variable from memory each time it's value is checked to ensure it doesn't continually read it from the register stack correct?
But why do you say or
Answer3:
|
I do have it defined as volatile. As I understand it that forces the compiler to load the variable from memory each time it's value is checked to ensure it doesn't continually read it from the register stack correct?
| |
Correct
|
But why do you say orAnswer4:
Vitaliy Liptchinsky wrote: |
|
I do have it defined as volatile. As I understand it that forces the compiler to load the variable from memory each time it's value is checked to ensure it doesn't continually read it from the register stack correct?
| |
Correct
|
But why do you say orAnswer5: The lock and volatile keywords have memory barrier semantics (see http://en.wikipedia.org/wiki/Memory_barrier, though note that the discussion of volatile w.r.t. C is not the same as volatile in the CLR where it does provide a full memory barrier across all processor cores). A lock block provides read/write memory barrier on entry/exit so an entire lock block is effectively equivalent to a full memory barrier.
Assigning x = false is guaranteed to be atomic in the CLR because it guarantees 32-bit alignment and Boolean is a 32-bit value.
Declaring the variable as volatile will ensure you get the latest version, though if you're not bothered about a few extra loops there's no real need to do that either. Answer6:
Greg Beech wrote: |
Assigning x = false is guaranteed to be atomic in the CLR because it guarantees 32-bit alignment and Boolean is a 32-bit value.Answer7:
CyrexCore2k wrote: |
|
|
| |
| | | |
| |