is assignment operation atomic?

  • Thread starter Thread starter Zeng
  • Start date Start date
Z

Zeng

Hello,

Is the assignment operation atomic? That is if one thread assigns to static
variable an object and another uses the object assigned to the variable,
would it be safe?

Thanks!
zeng
 
Zeng said:
Hello,

Is the assignment operation atomic? That is if one thread assigns to static
variable an object and another uses the object assigned to the variable,
would it be safe?

Do you mean that both events will not happen at the same exact time?

From what i've read with threads you can't guarantee anything -
imagine you run your app on a multiprocessor system - both events may happen at exact same time then.

With a single-processor systems, i think it's ok, but then it's not scalable.

Why wouldn't you use locks on the object?

ANdrey
 
Zeng said:
Is the assignment operation atomic? That is if one thread assigns to static
variable an object and another uses the object assigned to the variable,
would it be safe?

Even if the assignment were atomic (which depends on alignment) you
still wouldn't be guaranteed to see the latest version of the variable,
or indeed the latest version of the values within the object. You
should either make the field volatile, or use locks.

See http://www.pobox.com/~skeet/csharp/threads/volatility.shtml
 
Zeng said:
Is the assignment operation atomic? That is if one thread assigns to static
variable an object and another uses the object assigned to the variable,
would it be safe?

Assigment should be atomic for single-precision variables. That is, it
may take two instructions (load register from memory; write register
to memory) but the assigned variable is always in either the old state
or the new state, never half way between.

Otoh, this is not true for multiple-precision variables like long or
decimal, and if you're writing for CF, you really don't know what the
native precision is.

Use lock.
 
Back
Top