Passing a lock to another thread #119555
Replies: 4 comments 3 replies
-
Stupid alternate solution:
The lock must be locked. There is no reason this method would need to check if it's being called by two threads at once. |
Beta Was this translation helpful? Give feedback.
-
.... like what?
This is a recipe for deadlocks, because you could be sending the lock to a thread about to exit/crash/whatever, and now the lock is "lost" (and under no circumstances would a thread be able to "steal" a lock from whichever one already owns it, because that would be a recipe for an even larger disaster). It's somewhat unusual to work directly with In any case, lock handoffs between threads like you're suggesting are incredibly suspicious, implying that you're probably doing something wrong. |
Beta Was this translation helpful? Give feedback.
-
Just because an object implements IDisposable doesn't mean you have to use it in a Dispose pattern? You could just use it as you want and only dispose it if you know it's finished with... |
Beta Was this translation helpful? Give feedback.
-
@bencyoung-Fignum : The code path to actually get rid of it depends on the GC to finish the job. We know by the time Dispose is called, no new references to the object can be obtained; however existing threads could be about to call it. So the only thing that can actually release the object is the GC. Attempting to get rid of that is a whole-codebase transform if it can even be done at all. Since this is true of the main object, this is also true of the reader-writer lock within it. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
ReaderWriterLock implements IDisposable
ReaderWriterLockSlim implements IDisposable
I got myself into a place where this is massively inconvenient. So I wrote an implementation of a reader writer lock in terms of the managed locking primitives. It didn't work.
The reason it doesn't work may be understood as follows:
As a base check, I did the following:
That code ran through. There's no reason a priori why the method cannot function; but it won't function because the caller checks.
You're probably thinking this doesn't work anyway because the lock is recursive. In my case I can prove the second call to Enter isn't recursive.
Note that just knocking the check out is a bad idea. We would have to have more like a constructor argument to say "make a non-recursive lock that doesn't check".
Beta Was this translation helpful? Give feedback.
All reactions