Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using interlocked usage

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!

like image 696
kiki Avatar asked Mar 01 '12 14:03

kiki


2 Answers

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.)

like image 104
Branko Dimitrijevic Avatar answered Oct 03 '22 22:10

Branko Dimitrijevic


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);
like image 39
Scott Chamberlain Avatar answered Oct 03 '22 23:10

Scott Chamberlain