|
Here’s a quick brainteaser for you. Suppose you really want to find all the prime numbers in a certain range, and store them in a List<uint>. And also suppose that you want to parallelize that calculation to make it as quick as possible. You then need to synchronize access to the list so that it’s not corrupted by add operations performed in multiple threads. Would it be better to use a C# lock (CLR Monitor) or a Windows mutex to protect the list of primes? If you choose poorly, more processors actually make it slower.
|
|
|
|
|
Neither, you'd choose a list implementation that used an internal Critical Section to protect overlapped appends and didn't resort to a Mutex until it really needed to. Even then memory allocation strategy might well trump locking cost depending on how many primes we're talking about.
That won't work across processes of course but then you don't need a lock at all as others have pointed out.
"The secret of happiness is freedom, and the secret of freedom, courage."
Thucydides (B.C. 460-400)
modified 16-Jul-13 4:51am.
|
|
|
|
|
I wouldn't be using a Mutex in this example for the simple fact that the thing works acrossed process boundries. If you have a couple of instances running, each process can interfere with the others.
|
|
|
|
|
Poor implementation. No mutex or lock or critical section is needed. Simply have a separate list for each process that gets appended to a master list in the master process as each process completes.
If your actions inspire others to dream more, learn more, do more and become more, you are a leader.-John Q. Adams You must accept one of two basic premises: Either we are alone in the universe, or we are not alone in the universe. And either way, the implications are staggering.-Wernher von Braun Only two things are infinite, the universe and human stupidity, and I'm not sure about the former.-Albert Einstein
|
|
|
|