|
-
May 24th, 2011, 06:46 AM
#1
Locking depending on a variable value
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
-
May 24th, 2011, 09:29 AM
#2
Re: Locking depending on a variable value
You could always create a map of locks:
Code:
std::map <ObjectA, object>
Or:
Code:
std::map <std::string, object>
And using the object's ID as the key.
Viggy
-
May 26th, 2011, 02:24 AM
#3
Re: Locking depending on a variable value
 Originally Posted by mutenvo
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).
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|