Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C NSLock: lock and unlock a NSLock on different threads

I need to set a mutex before to make an asynchronous request, and then unlock the mutex in the callback of this request that is on another thread.

Apple documentation say:

Warning: The NSLock class uses POSIX threads to implement its locking behavior. When sending an unlock message to an NSLock object, you must be sure that message is sent from the same thread that sent the initial lock message. Unlocking a lock from a different thread can result in undefined behavior.

How can I avoid this "undefined behaviour" and make it work as expected?

like image 587
Giuseppe Avatar asked Dec 06 '22 20:12

Giuseppe


1 Answers

Better yet; use an NSOperationQueue or a GCD queue as your synchronization primitive.

Locks are expensive and semaphores are, more or less, a lock with a counter.

Queue based coding is far more efficient, especially when using the built in queuing mechanisms.

like image 141
bbum Avatar answered Mar 16 '23 00:03

bbum