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
精彩评论