Is DispatchSemaphore a good replacement for NSLock?

走远了吗. 提交于 2020-05-25 17:01:11

问题


I've been using NSLocks to synchronize touchy parts of code, but have been running into issues due to the fact that they must be unlocked from the same thread that they were locked from. Then I found that GCD's DispatchSemaphores seem to do the same thing, with the added convenience that they can be signaled from any thread. I was wondering, though, if this convenience comes at the price of thread-safety. Is it advisable to replace

let lock = NSLock()
lock.lock()
// do things...
lock.unlock()

with

let semaphore = DispatchSemaphore(value: 1)
semaphore.wait()
// do things...
semaphore.signal()

or will I run into issues regarding thread-safety anyway?


回答1:


Yes they have the same function, both to deal with producer-consumer problem.

Semaphore allows more than one thread to access a shared resource if it is configured accordingly. You can make the execution of the blocks in the same concurrent dispatchQueue.

{semaphore.wait()
// do things...
semaphore.signal()}

Actually the same applies to Lock, if you only want one thread to touch the resource at one time, in the concurrent way.

I found this to be helpful: https://priteshrnandgaonkar.github.io/concurrency-with-swift-3/




回答2:


Since asking this, I have mostly switched over to another way of locking blocks of code: serial dispatch queues. I use it like this:

let queue = DispatchQueue(label: "<your label here>")
queue.async {
    // do things...
}

The queue is serial by default, meaning it acts as a lock that releases when the block is exited. Therefore, it's not appropriate if you need to lock on an asynchronous operation, but it works a charm in most cases.



来源:https://stackoverflow.com/questions/43468647/is-dispatchsemaphore-a-good-replacement-for-nslock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!