Vala 中委托的异步作用域是什么?
What is an async scope for a delegate in Vala?
我正在尝试 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)
我正在尝试 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)