Reputation: 10447
What is most apropriate mutex alg in C#/.NET for this kind of task.
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.
Upvotes: 0
Views: 475
Reputation: 375
Although this is an old thread (post, whatever), I came across a unique approach to lock versus MutEx that is beneficial under certain circumstances.
If your collisions by multiple entities desiring access are infrequent, consider the following approach:
For example:
The idea is that if there are any activities that need to lock also but do not affect your code's outcome (admittedly, the example is not a good one for this case), you have not prevented that other code's execution.
There exists some hardware for this but it is no longer "mainstream:" the IBM System 370 had an atomic compare and update instruction for just this situation.
Upvotes: 1
Reputation: 48949
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.
Upvotes: 1
Reputation: 35604
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?
Upvotes: 0