I am trying to write a multithreaded program where each thread would use a counter and then increment it.
for example:
lock(this)
{
counter++;
Console.WriteLine(counter);
}
i know that for incrementation i can use:
System.Threading.Interlocked.Increment(counter);
but what about locking for both incrementing and doing something with the counter?
Thanks!
Doing this is OK:
Thread A:
var incremented_counter = Interlocked.Increment(ref counter);
Console.WriteLine(incremented_counter);
Thread B:
Interlocked.Increment(ref counter);
And doing this is OK:
Thread A:
lock (the_lock) {
++counter;
Console.WriteLine(counter);
}
Thread B:
lock (the_lock) {
++counter;
}
Doing this is OK but redundant:
Thread A:
lock (the_lock) {
var incremented_counter = Interlocked.Increment(ref counter);
Console.WriteLine(incremented_counter);
}
Thread B:
lock (the_lock) {
Interlocked.Increment(ref counter);
}
But doing this is not OK:
Thread A:
Interlocked.Increment(ref counter);
Console.WriteLine(counter);
Thread B:
Interlocked.Increment(ref counter);
Nor is it doing this:
Thread A:
lock (the_lock) {
++counter;
Console.WriteLine(counter);
}
Thread B:
Interlocked.Increment(ref counter);
Nor is it doing this:
Thread A:
var incremented_counter = Interlocked.Increment(ref counter);
Console.WriteLine(incremented_counter);
Thread B:
lock (the_lock) {
++counter;
}
(BTW, don't use lock
on this
.)
All of the Interlock functions return a copy of the value after modification, used that returned value during your thread.
var localCounter = System.Threading.Interlock.Increment(counter);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With