CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    May 2011
    Posts
    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

  2. #2
    Join Date
    Feb 2002
    Posts
    4,640

    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

  3. #3
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Locking depending on a variable value

    Quote Originally Posted by mutenvo View Post
    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
  •  





Click Here to Expand Forum to Full Width

Featured