swift中的互斥替代方案 [英] Mutex alternatives in swift

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

问题描述

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

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.

这个问题的一个解决方案是使用互斥锁.

One solution to this problem is to use Mutex.

正如我发现的,Swift 中没有互斥锁.Swift 中有其他选择吗?

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

推荐答案

正如人们所评论的(包括我),有几种方法可以实现这种锁定.但我认为 dispatch semaphore 比其他的更好,因为它似乎开销最少.如 Apples doc, "替换信号量代码",除非信号量已经锁定(= 零),否则它不会进入内核空间,这是代码进入的唯一情况内核来切换线程.我认为大多数时候信号量不是零(当然,这当然是应用程序特定的问题).因此,我们可以避免大量开销.

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.

再说明一下dispatch semaphore,和上面的情况正好相反.如果你的线程有不同的执行优先级,并且更高优先级的线程不得不长时间锁定信号量,调度信号量可能不是解决方案.这是因为等待线程之间没有队列".在这种情况下会发生什么是更高的优先级线程大部分时间获取并锁定信号量,而低优先级的线程只能偶尔锁定信号量,因此,大多数情况下只是等待.如果这种行为对您的应用程序不利,您必须考虑使用调度队列.

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.

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

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