我有归结为一个函数:设计模式,而循环
while(doWork)
{
config = generateConfigurationForTesting();
result = executeWork(config);
doWork = isDone(result);
}
我怎么能改写这个高效异步执行,假设所有的功能都是线程安全的,独立于以前的迭代,并且可能需要比最大允许线程数多的迭代次数?
这里的问题是我们不知道需要提前多少次迭代,所以我们不能使用dispatch_group
或使用dispatch_apply
。
这是我第一次尝试,但由于任意选择的值和睡觉,它看起来有点丑陋;
int thread_count = 0;
bool doWork = true;
int max_threads = 20; // arbitrarily chosen number
dispatch_queue_t queue =
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
while(doWork)
{
if(thread_count < max_threads)
{
dispatch_async(queue, ^{ Config myconfig = generateConfigurationForTesting();
Result myresult = executeWork();
dispatch_async(queue, checkResult(myresult)); });
thread_count++;
}
else
usleep(100); // don't consume too much CPU
}
void checkResult(Result value)
{
if(value == good) doWork = false;
thread_count--;
}
是的,我正在实施一种随机搜索算法;但它也可能是一种遗传优化的框架。 – koan 2013-05-14 19:52:04