在Swift中并发访问Array的元素

问题描述

我尝试以并发方式在Swift中读写数组(来自不同数组),并且在运行时发生写操作异常。 我在Objective-C ++中有并发模糊代码

- (cpp_blur::Bitmap)blur {
    Bitmap result(_source);
    auto indexes = [[NSIndexSet alloc] initWithIndexesInRange:NSMakeRange(0,_source.size())];
    int minIndex = 0;
    int maxIndex = static_cast<int>(result.size()) - 1;
    [indexes enumerateIndexesWithOptions:NSEnumerationConcurrent
                              usingBlock:[&](NSUInteger idx,BOOL* _Nonnull stop){
        double sum = 0.0;
        for (int i = static_cast<int>(idx) - static_cast<int>(self.radius); i <= idx + self.radius; i++) {
            int index = clamp(i,minIndex,maxIndex);
            sum += self->_source.at(index);
        }
        sum /= static_cast<double>(self.radius * 2 + 1);
        result.at(idx) = sum;
    }];

    return result;
}

我尝试在Swift中编写相同的代码

@objc public func blur() -> [Double] {
        var result = source
        let indexSet = NSIndexSet(indexesIn: NSMakeRange(0,source.count))
        let from = -Int(self.blurRadius)
        let to = Int(self.blurRadius)
        let lastIndex = self.source.count - 1
        indexSet.enumerate(options: .concurrent) { (index:Int,_) in
            let sum = ((from + index)...(to + index)).reduce(0.0) { (partial:Double,nonClamped:Int) -> Double in
                let index = self.clamp(nonClamped,min: 0,max: lastIndex)
                let result = partial + self.source[index]
                return result
            }
            let avg = sum / Double(2 * self.blurRadius + 1);
            result[index] = avg //here I have crash in runtime
        }

        return result
    }

如果我在result[index] = avg周围添加了锁,则该异常将消失,但是会出现性能问题。 如何在不锁定的情况下更改Swift数组中元素的值(同时我仅更改不同的元素)? Github repo.

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...