[Vala] gio-2.0.vapi: Async sleep



Moin

One of the problems of async methods is that you cannot use the normal
sleep method. That's why I wrote a small async sleep method. Maybe
there're some concurrency problems, I want to discuss here.

Regards, Frederik
using GLib;
public async void sleep_async(int timeout, GLib.Cancellable? cancellable = null) {
        ulong cancel = 0;
        uint timeout_src = 0;
        if (cancellable != null) {
             if (cancellable.is_cancelled ()) 
                    return;
             cancel = cancellable.cancelled.connect (()=>sleep_async.callback());
        }
        timeout_src = Timeout.add(timeout, sleep_async.callback);
        yield;
        Source.remove (timeout_src);

        if (cancel != 0 && ! cancellable.is_cancelled ()) {
                cancellable.disconnect (cancel);
        }
}
public async void test (Cancellable? c) {
        debug("before");
        //sleep 3s
        yield sleep_async (3000, c);
        debug("after");
}
void main () {
        var ml = new MainLoop ();
        var c = new Cancellable ();
        //c.cancel ();
        //unowned Thread t1 = Thread.create ( () => {Thread.usleep (2000000); debug ("cancel from thread"); c.cancel ();}, false);
        unowned Thread t2 = Thread.create ( () => {debug("starting test"); test(c);}, false);
        //cancel after 1 s
        Timeout.add (500, ()=> {debug("cancelled");c.cancel ();return false;});
        Timeout.add (5000, () => {ml.quit (); debug("quit");return false;});
        test (c);
        ml.run();
}

Attachment: signature.asc
Description: This is a digitally signed message part



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]