Search code examples
swiftgrand-central-dispatchdispatch-async

Parallel search with dispatch_async


I'm trying to implement a parallel-search algorithm. The concept is something like this:

  1. Start with a candidate & test if it is the desired value
  2. If not, generate more candidates and add them to the queue.
  3. Repeat until reaching the desired value

As a simplified example: I want to run a random number generator in the range 0..<n until it gives me 0. I want to decrease n with each iteration so success is guaranteed. This is my code so far:

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>'

I got two erros:

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

How can I fix them? Many thanks in advance!


Solution

  • You can fix the "used within its own initial value" by doing the declaration and initialization in two steps.

    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
        }
    }
    

    You can fix the other one like this.

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