Click to See Complete Forum and Search --> : Locking depending on a variable value


mutenvo
May 24th, 2011, 06:46 AM
Hi there
I've got a function like this:

class Test{

private readonly object _syncLock = new object();

void Work(ObjectA objectA){
lock (_syncLock){
while (objectA.IsBusy)
Monitor.Wait(_syncLock)
//Do some work...
Monitor.PulseAll(_syncLock);
}
}

If Test.Work() is doing some work with objectA1 and we call now Test.Work(objectA2),
it will have to wait until Test.Work(objectA1) is finished. As they both use the same sync object.

I would like to set a lock depending on the instance, i.e., something like lock(objectA), but this is not recommendable as objectA is public and we don't control the instance.

Is there any way of doing this?

I've found we can do it using a Mutex (pasing objectA.Id as string, for example) but this overkills what I want to achieve, as Mutex is more costly than a simple Lock, and it is recommended for process syncing..

Thanks

MrViggy
May 24th, 2011, 09:29 AM
You could always create a map of locks:
std::map <ObjectA, object>
Or:
std::map <std::string, object>
And using the object's ID as the key.

Viggy

Arjay
May 26th, 2011, 02:24 AM
If Test.Work() is doing some work with objectA1 and we call now Test.Work(objectA2),
it will have to wait until Test.Work(objectA1) is finished. As they both use the same sync object.No they don't - _syncLock is a per instance class field.

Calling new Test.Work(objectA2) will immediate execute (because its _syncLock is different from the _syncLock of the first Test instance).