【问题标题】:What is an async scope for a delegate in Vala?Vala 中委托的异步作用域是什么?
【发布时间】:2020-03-04 08:52:46
【问题描述】:

我正在尝试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 变量。谁或什么需要拥有?对闭包的引用?

【问题讨论】:

    标签: asynchronous vala


    【解决方案1】:

    代理需要始终有一个明确定义的所有者。错误信息有点误导。

    要修复它,您必须将所有权从委托显式转移到线程构造函数:

    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)

    【讨论】:

    • 我正在使用 valac 0.44.3 并且修复了警告。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-23
    • 2021-05-23
    • 1970-01-01
    • 2015-10-13
    • 1970-01-01
    • 2012-06-08
    • 2010-11-27
    相关资源
    最近更新 更多