multithreading - 如何在 Swift 中创建 volatile bool 值?

标签 multithreading swift atomic

我想在后台执行一些任务并添加取消任务的功能。

类似于:

while !isCanceled && someOtherCondition() {
    doSome()
}

并从另一个线程取消任务:

func cancel() {
    isCanceled = true
}

在Java中,我可以将isCancelled声明为 volatile 的,这就足够了。我怎样才能在 Swift 中做到这一点?

最佳答案

看来这就是你的答案:

Swift does not (yet) have a well-defined memory model, so there’s no direct equivalent of C’s volatile. Having said that, C didn’t have a well-defined memory model until C11 either, so you can go a long way without one.

https://forums.developer.apple.com/thread/46256

关于multithreading - 如何在 Swift 中创建 volatile bool 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34687797/

相关文章:

.net - 如何找出哪个线程拥有互斥锁?

ios - PFQueryTableViewController 中附加了重复值

ios - UIViewController 背景图像跨越导航栏后面?

java - 实现跨机器同步的良好设计是什么?

Java:通过多线程并行化快速排序

c# - 在主线程中设置线程本地值并在另一个线程中获取

java - 构建器模式的线程安全实现

ios - 为非半透明导航栏swift 4设置背景图片

java - 如何在 Java 中编写自定义原子方法?

c++ - 用于同步的条件变量与原子类型