Monday, May 2, 2011

Prepare for a move - threading and parallel

Finally, it is time to prepare for some move in the future. When you buried in everyday work, you must have got tunnel vision, I hope this preparation process will give me some fresh air. You might use the low performance statement every day or totally lose your mind when being ask what is "algorithm X" with O(n). :-) Let us start my journey and hopefully learn something new.

The first topic I want to touch is to use lock keyword in the C#.

if there are some variables in the class and how to use lock to update it.

if it is a int or long, use the interlock.increament if that is possible. Otherwise, the general rule is

1. declare a private or protected variable as syncroot
2. if the variable is value type, then lock the syncroot
if the variable is ref type, lock the variable itself.

Actually, if you want to get your work done, use the data structure under System.Collection.Concurrent namespace (new .net 4.0) , which is usually get rid of the need for explicit synchronization.

One catch I found is that on 32-bit system, the reading a 64-bit int is NOT atomic. You have to use Interlock.Read(). In a 64-bit system, reading 64-bit int is atomic.

Today I found the [ThreadStatic] attribute is very useful when design the multi-thread application. It has unique value for each thread!

No comments: