objective-c - Objective-C NSLock : lock and unlock a NSLock on different threads

标签 objective-c multithreading cocoa macos thread-safety

我需要在发出异步请求之前设置一个互斥锁,然后在另一个线程上的这个请求的回调中解锁互斥锁。

苹果文档说:

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.

如何避免这种“未定义的行为”并使其按预期工作?

最佳答案

更好的是;使用 NSOperationQueue 或 GCD 队列作为同步原语。

锁很昂贵,而信号量或多或少是带有计数器的锁。

基于队列的编码效率更高,尤其是在使用内置排队机制时。

关于objective-c - Objective-C NSLock : lock and unlock a NSLock on different threads,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6457045/

相关文章:

objective-c - 关于代表的问题

java - Java 中的进程——它们同时工作吗?

multithreading - 当我在 Clojure 中定义来自多个线程的变量时会发生什么?

xcode - 如何重新打开应用程序窗口,Xcode

swift - 以编程方式更改 Mac 光标速度

iphone - NSString 内部结构 - 长度如何工作?

iphone - 将 MIDI 源发布为 Bonjour 服务

objective-c - 归档/取消归档 NSTableViewController 数据的最佳实践?

ios - 在这个例子中使用内省(introspection)是正确的做法吗?

java - 做 runnable.run() 是不是错了?