本文介绍了如何在特定线程上锁定NSLock的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个属性 @property NSLock * myLock

我想写两个方法:

- (void) lock

- (void) unlock

这些方法分别锁定和解锁 myLock 他们需要这样做而不管什么线程或队列称它们。例如,线程A可能已调用 lock ,但队列B可能是调用 unlock 的队列。这两种方法都应该正常工作,而不报告我试图从锁定它的其他线程/队列中解锁锁。此外,他们需要同步执行此操作。

These methods lock and unlock myLock respectively and they need to do this regardless of what thread or queue called them. For instance, thread A might have called lock but queue B might be the one calling unlock. Both of these methods should work appropriately without reporting that I am trying to unlock a lock from a different thread/queue that locked it. Additionally, they need to do this synchronously.

推荐答案

NSLock 是适合这项工作的工具。现在有更好的工具,尤其是GCD;更晚些时候。

It is rare anymore that NSLock is the right tool for the job. There much better tools now, particularly with GCD; more later.

您可能已经从,但我会重复阅读:

As you probably already know from the docs, but I'll repeat for those reading along:

如果您尝试锁定,那么如果没有死锁则很难实现并在不同的线程上解锁。根本问题是,如果 lock 阻塞该线程,那么后续的 unlock 就无法运行那个线程,你不能在另一个线程上解锁 NSLock 不适用于此问题。

That's very hard to implement without deadlocking if you're trying to lock and unlock on different threads. The fundamental problem is that if lock blocks the thread, then there is no way for the subsequent unlock to ever run on that thread, and you can't unlock on a different thread. NSLock is not for this problem.

而不是 NSLock ,您可以使用 dispatch_semaphore_create()实现相同的模式。这些可以在您喜欢的任何线程上安全地更新。您可以使用 dispatch_semaphore_wait()锁定,并且可以使用 dispatch_semaphore_signal()解锁。也就是说,这个仍然通常不是正确的答案。

Rather than NSLock, you can implement the same patterns with dispatch_semaphore_create(). These can be safely updated on any thread you like. You can lock using dispatch_semaphore_wait() and you can unlock using dispatch_semaphore_signal(). That said, this still usually isn't the right answer.

大多数资源争用最好用操作队列或调度队列来管理。这些提供了并行处理工作,管理资源,等待事件,实现生产者/消费者模式以及使用 NSLock 完成的几乎所有操作的出色方法。过去 NSThread 。我强烈推荐作为如何设计队列而不是锁。

Most resource contention is best managed with an operation queue or dispatch queue. These provide excellent ways to handle work in parallel, manage resources, wait on events, implement producer/consumer patterns, and otherwise do almost everything that you would have done with an NSLock or NSThread in the past. I highly recommend the Concurrency Programming Guide as an introduction to how to design with queues rather than locks.

这篇关于如何在特定线程上锁定NSLock的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-22 22:21