开发者

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

开发者 https://www.devze.com 2023-03-14 19:10 出处:网络
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.

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?


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.


Use a NSCondition for this to signal other threads that they can safely pass now.


Don't use a mutex for this. Use a semaphore initialized to 1 or some other lock mechanism that allows cross-thread communication/locking.

Rgds, Martin

0

精彩评论

暂无评论...
验证码 换一张
取 消