我正在尝试async examples from the GNOME project site。我收到以下警告,但我不知道如何解决。
async.vala:8.2-8.17: warning: delegates with scope="async" must be owned
代码
async double do_calc_in_bg(double val) throws ThreadError {
SourceFunc callback = do_calc_in_bg.callback;
double[] output = new double[1];
// Hold reference to closure to keep it from being freed whilst
// thread is active.
// WARNING HERE
ThreadFunc<bool> run = () => {
// Perform a dummy slow calculation.
// (Insert real-life time-consuming algorithm here.)
double result = 0;
for (int a = 0; a<100000000; a++)
result += val * a;
output[0] = result;
Idle.add((owned) callback);
return true;
};
new Thread<bool>("thread-example", run);
yield;
return output[0];
}
void main(string[] args) {
var loop = new MainLoop();
do_calc_in_bg.begin(0.001, (obj, res) => {
try {
double result = do_calc_in_bg.end(res);
stderr.printf(@"Result: $result\n");
} catch (ThreadError e) {
string msg = e.message;
stderr.printf(@"Thread error: $msg\n");
}
loop.quit();
});
loop.run();
}
该警告指向异步函数内的run
变量。谁或什么需要拥有?引用关闭?
委托人必须始终具有明确定义的所有者。错误消息有点误导。
要修复它,您必须将所有权从委托显式转移到线程构造函数:
new Thread<bool>("thread-example", (owned) run);
代替
new Thread<bool>("thread-example", run);
另请参见:https://wiki.gnome.org/Projects/Vala/Tutorial#Ownership
PS:生成的C代码在两种情况下都可以。 (至少使用valac 0.46.6)