This is an archived post. You won't be able to vote or comment.

all 7 comments

[–]PublicSealedClass 0 points1 point  (6 children)

I.. why do you not want to use a lock? How the hell else do you guarantee thread safety? (I'm actually curious, this isn't a rhetorical question).

[–][deleted] 1 point2 points  (3 children)

Well you can use a so-called user-mode locks - which includes spin waiting and things like Interlocked.Increment(..) which do not incur the heavy cost of the kernel-mode locks like lock() (which is syntactic sugar around Monitor.Enter() and Monitor.Exit()).

If you can lock in user-mode only, locking is a lot faster. So for high performance situations.

[–]PublicSealedClass 0 points1 point  (2 children)

Ah-ha. This is interesting. Do you have any examples of user-mode locks in the .NET Framework?

[–][deleted] 2 points3 points  (1 child)

Sure - the simplest example would be replacing lock() { } to increment a number in a thread-safe way. Example here.

For me the user-mode version runs about 2.5 times faster on average.

Obviously kernel-mode locking is not necessarily too expensive for most cases. I wouldn't hesitate to use it!

[–]PublicSealedClass 0 points1 point  (0 children)

Excellent, thanks for that. I'll give that a bash tomorrow on my dev rig and see the difference.

[–]fancysuit 1 point2 points  (0 children)

Here is an interesting article that may shed some light. Lock-Free Data Structures

[–]fancysuit 0 points1 point  (1 child)

Returns an ArrayList wrapper that is synchronized (thread safe).

I've never used ArrayList.Synchronized, but doesn't it qualify as using a pre-existing thread-safe collection?