使用 dispatch_async 进行并行搜索
Parallel search with dispatch_async
我正在尝试实施并行搜索算法。这个概念是这样的:
- 从候选人开始并测试它是否是所需的值
- 如果没有,生成更多候选人并将他们添加到队列中。
- 重复直到达到所需值
作为一个简化的例子:我想 运行 范围内的随机数生成器 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>'
我该如何修复它们?非常感谢!
您可以通过分两步进行声明和初始化来修复"used within its own initial value"。
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)
我正在尝试实施并行搜索算法。这个概念是这样的:
- 从候选人开始并测试它是否是所需的值
- 如果没有,生成更多候选人并将他们添加到队列中。
- 重复直到达到所需值
作为一个简化的例子:我想 运行 范围内的随机数生成器 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>'
我该如何修复它们?非常感谢!
您可以通过分两步进行声明和初始化来修复"used within its own initial value"。
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)