is assignment operation atomic?

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
 
M

MuZZy

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
 
J

Jon Skeet [C# MVP]

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
 
J

Jon Shemitz

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top