Question

I have a multithread running context. I want one resource (let's say Object r) to be mutual exclusive. Can I use the resource itself as its monitor object?

e.g.

    lock(r)
    {
        // do something...
    }
Was it helpful?

Solution

If r stays the same object throughout - for example, r is a List that you're adding items to from several threads:

lock (r)
{
    r.Add("Hello world");
}

then this is fine - it doesn't cause any issues, and you can read it as you're specifically "locking r". (Just make sure you put a similar lock around any other code that's using r too.)

However, if r is being switched for another object inside the lock:

lock (r)
{
    r = new List<string>();
}

this isn't a good idea, because you could end up with two threads running the lock against two different versions of r. In this case, you should create an unchanging object specifically to lock against - you're more "locking the code block" than "locking r".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top