Reputation: 6756
lets suppose there is a static variable accessed by 2 threads.
public static int val = 1;
now suppose thread 1 execute's a statement like this
if(val==1)
{
val +=1
}
However after the check and before the addition in the above statement thread 2 changes the value of val to something else.
Now that would cause some nasty error. And this is happening in my code.
Is there any way that thread 1 gets noticed that the values of val has been changed and it instead of adding goes back and performs the check again.
Upvotes: 1
Views: 627
Reputation: 3297
If you wish to increment an integral value in a thread-safe way, you can use the static Interlocked.Increment
method: Interlocked.Increment Method (Int32)
Upvotes: 0
Reputation: 120450
Specifically for your example, you could:
var originalValue = Interlocked.CompareExchange(ref val,
2, //update val to this value
1); //if val matches this value
if(originalValue == 1)
{
//the update occurred
}
Upvotes: 6
Reputation: 245429
You could use a lock:
var lockObj = new object();
if(val == 1) // is the value what we want
{
lock(lockObj) // let's lock it
{
if(val == 1) // now that it's lock, check again just to be sure
{
val += 1;
}
}
}
If going that route, you'll have to make sure any code that modifies val
also uses a lock with the same lock object.
lock(lockObj)
{
// code that changes `val`
}
Upvotes: 3
Reputation: 41
You could use a lock around accessing val or updating val. See http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim.aspx
Upvotes: 0