Several locks in one thread, why might they be needed? [duplicate] - c#

This question already has answers here:
When would you ever use nested locking?
(3 answers)
Closed 11 months ago.
It says here :
While a lock is held, the thread that holds the lock can again acquire and release the lock.
Question. For what purpose can several consecutive locks be used in one thread? Or does it give nothing, but the article says to clarify that inside one thread the code in the second lock will also be executed because the lock is used in the same thread?
I just want to understand the purpose of this information.

Its called recursive locking. It is useful if you have complex paths that may end up trying to lock a resource twice (like in a recursive function). It saves you have to keep track of whether or not you already have a lock.
It is typically implemented as a counter, after the first lock subsequent locks just increment the counter, unlocks decrement, when the count reaches 0 the mutex is released

Related

C#: What happens if I try to lock a locked object? [duplicate]

This question already has answers here:
What does a lock statement do under the hood?
(9 answers)
Closed 5 years ago.
for example--
Object obj = new Object();
then I lock one section with lock(obj)
and I lock in other section also lock(obj)
if one thread is in the first section, does that mean that the other section is also locked?
Locking is done on an object, not on a section or location of the code. If one thread takes the lock in the first location, the second thread can't take it anywhere - neither in the same location and nor in any other location.

lock(variable) - conflicting explanation of the variable [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
The docs don't explain it. They only say what should be locked on and what not.
From here it seems like the same object should be used by all threads for the lock to work. While from here it seems that that is exactly what should be avoided to prevent deadlock.
Keep in mind that I might be misunderstanding this whole matter of lock, because I just asked a question about how to "lock" a variable and got what seems to me not to achieve that at all (except locking code).
Think of a lock as a "talking stick" that is used in some meetings. Whoever is holding the stick can talk. Anyone that wants to talk must wait until the speaker relinquishes the stick.
When a piece of code acquires a lock on an object, any other piece of code that requests a lock on that same object must wait until the original code releases the lock.
So which object should you lock? It depends greatly on the context. The rule of thumb is you lock an object that anyone else who could affect the code block can lock as well. If you're updating a collection, then you can ICollection.SyncRoot as an example.
EDIT by OP (Hopefully correct):
"Anyone that wants to talk" - As the speaker "of that stick". (Anyone can just talk.)
As for the second link in the question - it's referring to a problem of one lock waiting for a second, while the second is waiting for the first.
lock should be used around any shared resource. By "shared resource" I mean anything that is accessed by more than one thread.
All a lock does is:
Incoming thread wants access to a piece of code, encounters lock
Lock is empty, thread is allowed in
Thread gets switched out
Another thread wants access to the same code (or code locked on the same variable), encounters lock
Variable is already locked, thread has to wait
Original thread is switched back in, exits locked code
Second thread is switched back in, executes the locked code
If it is possible to have threads in a lock and waiting on another lock at the same time, that then waits on the first lock, you have a gridlock condition. Typically you don't "nest" your locks to avoid this problem. Also, for performance if nothing else, you rarely lock on the same variable as another unless you actually have both pieces relying on the code not executing concurrently (probably a bad design if it is so :) )
Locking something is intended to protect a piece of shared memory. So, you have to use the same SyncRoot for a specific element that you are protecting... However, say you have 3 objects that need to be protected, and they are in no way related:
A a = new A();
B b = new B();
C c = new C();
Then there is NO reason to use the same SyncRoot for all 3 of them. In fact, if they are truly separate, it would be inefficient.

Does C# stores references to tasks from TPL [duplicate]

This question already has answers here:
Can .NET Task instances go out of scope during run?
(2 answers)
Closed 8 years ago.
Lets assume I run such a code
Task.Factory.StartNew(...).ContinueWith(...);
I don't store reference for neither of two created tasks so can I be sure that they won't be disposed before starting or at the process of executing? If yes then where do reference to these tasks are being held?
A reference to a TPL Task is held by the system under two conditions:
The Task is scheduled
The Task is running
Upon completion of the Task and any child tasks, the reference is thrown away. References in your code will behave as expected.
I believe you have some confusion regarding garbage collection and Dispose. This question may enlighten you.
Difference between destructor, dispose and finalize method
Destructor implicitly calls the Finalize method, they are technically same. Dispose is available with those object which
implements IDisposable interface...
Should you dispose Tasks?
Stephen Toub says:
No. Don’t bother disposing of your tasks.
https://devblogs.microsoft.com/pfxteam/do-i-need-to-dispose-of-tasks/

A good reason to use lock (this)? [duplicate]

This question already has answers here:
Why is lock(this) {...} bad?
(18 answers)
Closed 9 years ago.
There are many posts, votes and answers indicating using lock (this) is not a recommends pattern (not to mention a bad one).
Have a look at this one, for example.
As I'm trying to investigate this pattern a little bit, and wanted to ask whether anyone someone can think of a scenario in which using lock (this) is actually recommended, or even a must?
Locking on THIS is evil. This means that someone may decide to lock on your instance. This means that your instance will wait until someone else releases it.
Rule of thumb: never lock on this but create a seperate (private) object to lock.
But... The problem is deeper: locking has a purpose, by locking you provide protection on the upper object(s) but it doesn't prevent updating the underlying objects in for instance a collection.
In most cases a lock isn't a need. Read up on the subject is what I suggest.
Multiple questions on SO cover you question. Shouldn't be hard to build an opinion about the motivation to not lock on this.
An example and pointers for further reading can be found on the blog of Phil Haack

Auto- vs ManualResetEvent, differences [duplicate]

This question already has answers here:
What is the difference between ManualResetEvent and AutoResetEvent in .NET?
(11 answers)
Closed 9 years ago.
I read about event, which allow me to wait for other thread: AutoResetEvent and ManualResetEvent.
What are the differences between these two classes? Which class is better for a highly concurrent program?
The difference is in what happens when the event is signaled (set).
the manual-reset event will stay signaled until your explicitly reset it again
the auto-reset event will automatically get reset (unsignaled) once the first thread waiting for it gets awaken
In general I find it easier to work with manual reset events because in most cases it is a bit more straight-forward to determine the state of the event at any given time.
That said there are cases when the behavior of the auto-reset event lends itself better to achieving synchronization because you are guaranteed that only one of the waiting threads will be signaled. So if you have a producer/multiple-consumers scenario where any, but only, one consumer should be signaled you should consider the auto-reset event.

Categories