使用dispatch_async进行并行搜索

时间:2015-11-01 15:34:40

标签: swift grand-central-dispatch dispatch-async

我试图实现并行搜索算法。这个概念是这样的:

  1. 从候选人开始测试它是否是所需的值
  2. 如果没有,请生成更多候选人并将其添加到队列中。
  3. 重复直至达到所需的值
  4. 作为一个简化示例:我想在0..<n范围内运行一个随机数生成器,直到它给出0.我希望每次迭代减少n,这样才能保证成功。到目前为止,这是我的代码:

    let queue = dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0)
    let work : dispatch_function_t = { arg in
        let upper = UnsafeMutablePointer<UInt32>(arg).memory
        let random = arc4random_uniform(upper)
        if random == 0 {
            // do things
        } else {
            dispatch_async_f(queue, &(upper - 1), work)
            // Error: Variable used within its own initial value
        }
    }
    
    dispatch_async_f(queue, &1000, work)
    // Error: '&' used for non inout argument of type 'UnsafeMutablePointer<Void>'
    

    我有两个错误:

    Variable used within its own initial value
    '&' used for noninout argument of type 'UnsafeMutablePointer<Void>'
    

    我该如何解决?非常感谢提前!

1 个答案:

答案 0 :(得分:0)

您可以通过两个步骤进行声明和初始化来修复“在其自己的初始值中使用”。

let work: dispatch_function_t
work  = { arg in
    let upper = UnsafeMutablePointer<UInt32>(arg).memory
    let random = arc4random_uniform(upper)
    if random == 0 {
        // do things
    } else {
        dispatch_async_f(queue, &(upper - 1), work)
        // Error: Variable used within its own initial value
    }
}

你可以像这样修复另一个。

var n = 1000
dispatch_async_f(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), &n, work)