I'm trying to implement a parallel-search algorithm. The concept is something like this:
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!
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)