iphoneobjective-ciossynchronizationnslock

IOS SDK - NSLock message: "unlocked from thread which did not lock it"


I´m getting this error using NSLock which I tried to circumvent by using unlockWithCondition (using NSConditionLock), but regardless I get the same result:

* Break on _NSLockError() to debug. * -[NSLock unlock]: lock ( '(null)') unlocked from thread which did not lock it.

I´m not sure if it´s bad, but what I´m doing is this:

new Thread:
[lockA lock];//waiting unlock
[lockB lock];//waiting unlock
..shared code..
[lockA unlock];
[lockB unlock];

in Main Thread:
//Do two HTTP request.

//when request respond, I unlock the locks in respective threads with [lockA unlock];
[lockB unlock];

So the section "..shared code.." can execute. I don´t understand why i´m getting this error.

Can anyone explain what I´m doing wrong? It´s look like it should work perfectly.


Solution

  • I think you're trying to use locks as semaphores here. Locks are meant to stop the background thread and the main thread from accessing something simultaneously. Hence, the thread holding the lock must release (unlock) it too.

    If you want the background thread to wait for something to happen on the main thread, use semaphores.

    Use GCD semaphores for nice and easy semaphores: https://developer.apple.com/library/ios/#documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationQueues/OperationQueues.html