views:

56

answers:

3

What is most apropriate mutex alg in C#/.NET for this kind of task.

  • many reads
  • few incremental changes (up to 3 in "go forward" state machine )
  • very low collision probability (does collision probability matter?).

I was thinking about simple lock or ReaderWriterLockSlim , but I am not sure which one to choose and if there is something better for this task.

Thanks.

A: 

I don't know about ReaderWriterLockSlim especially, but a reader writer mutex can be used if multiple reads are allowed to access the critical section in parallel. If that assumption is true, depends on our use case. This is often, but not always the case.

If the assumption is meet, a reader write mutex should be a good fit.

What do you mean by "collision probability" in that context? The probability that two threads try to access the critical section concurrently?

dmeister
Probability is so low that is unlikley even in very long run and is much lower than ((acessing time)/(runtime))^(Number of treads)
ralu
A: 

What sort of data you are protecting.

If it's simple int , float data, you can use Interlocked classes,For atomic operations.

saurabh
+1  A: 

You are going to need to perform your own benchmarks. I think you will find that in most cases a plain old lock will be faster than a ReaderWriterLockSlim even if most of the accesses qualify as read-only. The reason being that the overhead of servicing the lock is a lot higher. It has been awhile since I did the benchmarks, but I believe the ReadWriterLockSlim was about 5x slower than a lock. Obviously, holding the lock longer will reduce the overall impact of the overhead. At some point it stops being the dominating factor. Mileage will vary from one situation to another so benchmarking on your own is about the best advice I can give here.

Brian Gideon
It is really short and fast algorhitm and in most cases i need that for really short time, just to change state enum.
ralu
Then I also would support Brian's answer. Even a spin lock might be a good fit. Has C# spin locks? Or even a raw compare_and_swap operation might be enough.
dmeister
@dmeister: Yep, the .NET BCL contains the `Interlocked.CompareExchange` and `SpinLock` classes.
Brian Gideon