gpt4 book ai didi

Swift 全局变量线程安全

转载 作者:搜寻专家 更新时间:2023-10-31 22:55:24 26 4
gpt4 key购买 nike

我知道,全局变量“不性感”,但我目前的项目很少。我试用了 Xcode 的 Thread Sanitizer,发现它们存在数据竞争。所以我试图让它们成为线程安全的。

因为我也想对这个变量进行单点管理。我试图在变量的 getter 和 setter 中做 GCD 的事情。

最后我找到了一个有效的解决方案,被编译器接受并且 Thread Sanitizer 很高兴......但是......这个解决方案看起来很丑陋(见下文)并且非常慢(做了性能测试并且它非常慢)。

是的,我知道,如果我为此使用类,它可能会更“敏捷”,但对于线程安全的全局变量必须有一个简单的解决方案。

所以你会这么好心并给出提示和建议来优化这个尝试吗?欢迎任何提示/想法/建议/评论!

// I used a "computed variable", to overcome the compiler errors, 
// we need a helper variable to store the actual value.
var globalVariable_Value : Int = 0

// this is the global "variable" we worked with
var globalVariable : Int {

// the setter
set (newValue) {
globalDataQueue.async(flags: .barrier) {
globalVariable_Value = newValue
}
}

// the getter
get {
// we need a helper variable to store the result.
// inside a void closure you are not allow to "return"
var result : Int = 0
globalDataQueue.sync{
result = globalVariable_Value
}
return result
}
}

// usage
globalVariable = 1
print ("globalVariable == \(globalVariable)")

globalVariable += 1
print ("globalVariable == \(globalVariable)")

// output
// globalVariable == 1
// globalVariable == 2

最佳答案

OOPer 要求我重做性能测试,因为发现结果很奇怪。

嗯,他是对的。我确实写了一个简单的应用程序(Performance Test App on GitHub)并附上了一些屏幕截图。

我在装有最新 IOS 的 iPhone SE 上运行该测试。该应用程序是在设备上启动的,而不是在 Xcode 中。对于所有显示的测试结果,编译器设置都是“调试”的。我也用“完全优化”(最小最快的 [-Os])进行了测试,但结果非常相似。我认为在简单的测试中没有太多需要优化的地方。

测试应用仅运行上述答案中描述的测试。为了让它更真实一点,它在三个并行的异步分派(dispatch)队列上使用 qos 类 .userInteractive、.default 和 .background 进行每个测试。

可能有更好的方法来测试这些东西。但是对于这个问题的目的,我认为已经足够了。

如果有人重新评估代码并找到更好的测试算法,我很高兴……我们都会从中学习。我现在停止我的工作。

结果在我看来很奇怪。所有三种不同的方法都提供了大致相同的性能。每次运行都有另一个“英雄”,所以我认为它只是受到其他后台任务等的影响。所以即使是 Itai Ferber “不错”的解决方案在实践中也没有任何好处。它“只是”一个更优雅的代码。

是的,线程保存解决方案比非排队解决方案慢得多。

这是主要的学习:是的,可以使全局变量线程安全,但它存在一个显着的性能问题。

Test with 100 iterations

Test with 1_000 iterations

Test with 10_000 iterations

Test with 100_000 iterations

关于Swift 全局变量线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48968423/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com