How to lock/synchronize a basic type

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,

I have several threads that write to the same int. Each thread increment the
integer value. What is the simple way to synchronize the increment operation.
The lock statement works only on Object so i can't use it. I tried also the
following:

private void incSimpleType(ref int n)
{
Monitor.Enter(n);
n+= 1;
Monitor.Exit(n);
}

It gives me the following error:
Object synchronization method was called from an unsynchronized block of code.

Please help me.
Thanks!
 
Thanks. But as i understand the Interlocked.Increment is incrementing only by
1. I want to increment the value with any value not just by 1. How can i do
that ?
 
How about something like:

private static Object _lock = new Object();

private static void incSimpleType(ref int n)
{
lock(_lock)
{
n+= 1;
}
}
 
Hello barbutz,

By the way, u need not syncronize operations with INT, it's atom it .net
(in case if align was not changed)

b> I have several threads that write to the same int. Each thread
b> increment the integer value. What is the simple way to synchronize
b> the increment operation. The lock statement works only on Object so i
b> can't use it. I tried also the following:
b>
b> private void incSimpleType(ref int n)
b> {
b> Monitor.Enter(n);
b> n+= 1;
b> Monitor.Exit(n);
b> }

---
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/members/laflour

"At times one remains faithful to a cause only because its opponents do not
cease to be insipid." (c) Friedrich Nietzsche
 
Michael said:
Hello barbutz,

By the way, u need not syncronize operations with INT, it's atom it .net
(in case if align was not changed)

Michael,

Yes, reads and writes on Int32 are atomic, but atomicity is rarely the
only requirement when multiple threads are involved. One should be
thinking about memory volatility as well. See the following article
for more information.

<http://www.yoda.arachsys.com/csharp/threads/volatility.shtml>

Brian
 
Back
Top