Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSLock - should just block when locking a locked lock?

Tags:

cocoa

nslock

I have a loop which starts with a

[lock lock];

because in the body of the loop I am creating another thread which needs to finish before the loop runs again. (The other thread will unlock it when finished).

However on the second loop I get the following error:

2011-02-02 07:15:05.032 BLA[21915:a0f] *** -[NSLock lock]: deadlock (<NSLock: 0x100401f30> '(null)')
2011-02-02 07:15:05.032 BLA[21915:a0f] *** Break on _NSLockError() to debug.

The "lock" documentation states the following:

Abstract: Attempts to acquire a lock, blocking a thread’s execution until the lock can be acquired. (required)

which makes me think it would just block until the lock could be acquired?

like image 671
Nippysaurus Avatar asked Feb 01 '11 21:02

Nippysaurus


People also ask

Does NSLock block the thread?

An NSLock is a mutex; it prevents multiple threads from accessing the same resource simultaneously, which is exactly what you want to do here. Once one thread acquires the lock, other threads attempting to acquire the lock will wait until the first thread releases the lock.

When to use NSLock?

An NSLock object can be used to mediate access to an application's global data or to protect a critical section of code, allowing it to run atomically.

Is NSLock thread safe?

Yes, it's safe to use NSLock from any thread, including the main thread. The only constraint with NSLock is that you must unlock it from the same thread that you locked it, which you are doing here.

What is NSRecursiveLock?

NSRecursiveLock defines a lock that may be acquired multiple times by the same thread without causing a deadlock, a situation where a thread is permanently blocked waiting for itself to relinquish a lock.


1 Answers

Sounds like two problems:

  • Locking a lock on one thread and unlocking on another is not supported – you probably want NSCondition. Wait on the NSCondition in the parent thread, and signal it in the child thread.
  • A normal NSLock can’t be locked while already locked. That’s what NSRecursiveLock is for.
like image 65
Jens Ayton Avatar answered Sep 20 '22 08:09

Jens Ayton