快速的互斥量替代方案 [英] Mutex alternatives in swift

查看:192
本文介绍了快速的互斥量替代方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在多个线程之间有一个共享内存.我想防止这些线程同时访问此内存. (例如生产者-消费者问题)

I have a shared-memory between multiple threads. I want to prevent these threads access this piece of memory at a same time. (like producer-consumer problem)

问题:

一个线程将元素添加到队列中,另一个线程读取这些元素并将其删除.他们不应同时访问队列.

A thread add elements to a queue and another thread reads these elements and delete them. They shouldn't access the queue simultaneously.

解决此问题的一种方法是使用Mutex.

One solution to this problem is to use Mutex.

我发现,Swift中没有Mutex. Swift中还有其他选择吗?

As I found, there is no Mutex in Swift. Is there any alternatives in Swift?

推荐答案

正如人们评论(包括我在内)那样,有几种方法可以实现这种锁定.但是我认为调度信号比其他信号更好,因为它似乎开销最少.如苹果,除非信号量已被锁定(= 0),否则它不会进入内核空间,这是唯一的情况内核切换线程.我认为信号量在大多数情况下都不为零(不过,这当然是应用程序特定的问题).因此,我们可以避免很多开销.

As people commented (incl. me), there are several ways to achieve this kind of lock. But I think dispatch semaphore is better than others because it seems to have the least overhead. As found in Apples doc, "Replacing Semaphore Code", it doesn't go down to kernel space unless the semaphore is already locked (= zero), which is the only case when the code goes down into the kernel to switch the thread. I think that semaphore is not zero most of the time (which is of course app specific matter, though). Thus, we can avoid lots of overhead.

关于调度信号量的另一条评论,与上面的情况相反.如果您的线程具有不同的执行优先级,并且更高优先级的线程必须长时间锁定信号量,则分派信号量可能不是解决方案.这是因为等待的线程之间没有队列".在这种情况下发生的是更高的优先级 线程大多数时候会获取并锁定信号量,而优先级较低的线程只能偶尔锁定信号量,因此,大多数情况下只是等待.如果此行为对您的应用程序不利,则必须考虑调度队列.

One more comment on dispatch semaphore, which is the opposite scenario to above. If your threads have different execution priorities, and the higher priority threads have to lock the semaphore for a long time, dispatch semaphore may not be the solution. This is because there's no "queue" among waiting threads. What happens at this case is that higher priority threads get and lock the semaphore most of the time, and lower priority threads can lock the semaphore only occasionally, thus, mostly just waiting. If this behavior is not good for your application, you have to consider dispatch queue instead.

这篇关于快速的互斥量替代方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆