views:

39

answers:

2

Hi,

I am working on multithreaded code. Data access is locked in several sections via "NSLock" objects. I want to ensure that some methods which are called within these sections check if their appropriate lock was aquired.

Something like:

assert([myLock isSet] == YES);

I can't find something like "isSet" in NSLock. Any ideas how to ensure a lock is set?

Thanks!

+2  A: 

How are you acquiring the lock? If you're calling lock, then the fact that you're even running afterwards should guarantee you've acquired it. If you call lockBeforeDate, the return value tells you.

If you want to test from elsewhere, you could do

if ( [myLock tryLock] )
{
    // oops, lock was not previously acquired!
    ...
    [myLock unlock];
}
else
{
    // yep, lock was already acquired
}

However, in general this seems like a questionable thing to want to do. You should do the locking where it's needed and trust it to work rather than trying to oversee it from the outside.

walkytalky
Thanks. tryLock is exactly what I want.I can do: assert(![myLock tryLock]);I do understand that this tells me that the object is "locked". It does not tell me if the right thread has the lock. Moreover I agree with you that this is a questionable thing to do. But I am desperately trying to find a bug (I don't think the bug is locking related, but I can't find anything wrong in the other code either - so I have to check locking).
Lars Schneider
Lars Schneider: `tryLock` does exactly what it says: It tries to lock the lock. If it succeeds, that doesn't just mean it wasn't locked before, it also means *it is now locked*. That's why you need to unlock it if it succeeds: Otherwise, you're holding the lock when you may not want to.
Peter Hosey
+1  A: 

No.

Because, you see, whatever result you get is useless, because it may (will) be wrong by the time you get around to actually using it. An example:

  1. You find that the lock is locked.
  2. The thread that held the lock unlocks it.
  3. You report that the lock is locked.

It fails the other way, too:

  1. You find that the lock is not locked.
  2. Another thread locks the lock.
  3. You report that the lock is unlocked.

Problems like this are exactly why debugging deadlocks and race conditions is so damned tricky.

I think you should ask another question about your actual problem.

Peter Hosey