synchronization issue

  • Thread starter Thread starter cristalink
  • Start date Start date
C

cristalink

The below is perfectly OK in C++, but I wonder how safe is it C#. There are
cases when one thread is writing to, another one is reading from the same
variable. I don't want/need to synchronize the access.

My question is, can the .NET framework handle this scenario, or it may throw
an exception? I realize the data may be out of sync (say, a half of the
variable contains new data, another half contains old data), but it's not an
issue.

Thanks



uint64 var = 0;

thread1_Write()
{
while(true)
{
var = random();
}
}


thread2_Read()
{
while(true)
{
Console.Write("{0}", var);
}
}
 
cristalink said:
The below is perfectly OK in C++, but I wonder how safe is it C#.

Well, that depends on what you mean by safe. Your definition appears to
be a lot looser than mine. :)
There are cases when one thread is writing to, another one is reading
from the same variable.

The variable you've given is a long, which can't be made volatile. If
you're using a variable which could be declared volatile, you'd be
okay.
I don't want/need to synchronize the access.

Is this for performance reasons? If so, I *strongly* recommend that you
write code with full synchronization first and measure its performance.
Locking is very fast.
My question is, can the .NET framework handle this scenario, or it may throw
an exception? I realize the data may be out of sync (say, a half of the
variable contains new data, another half contains old data), but it's not an
issue.

You won't get an exception, but you might get half-changed data, or
worse you might not even see the new data at all from the reading
thread.

See http://www.pobox.com/~skeet/csharp/threads/volatility.shtml for
more information.
 
cristalink said:
The below is perfectly OK in C++, but I wonder how safe is it C#.

The code should behave the same in C++ and C# on a 32-bit machine - it's
possible to get partial reads and writes to var, where one half is read
while the other half is written to.

As far as exceptions or whatever, no, there'll be no exceptions.

-- Barry
 

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

Back
Top