diff --git a/vala/threads/async_ex.vala b/vala/threads/async_ex.vala index 884b464..669b55a 100644 --- a/vala/threads/async_ex.vala +++ b/vala/threads/async_ex.vala @@ -1,9 +1,8 @@ -async void long_operation() {} - -async void async_method(int idx, int max, MainLoopKeeper mlk) { +async void do_smth () {} +async void async_method(int idx, int max, int step, MainLoopKeeper mlk) { for(var i = 0; i < max; ++i) { - stdout.puts(@"async$idx:$i\n"); - yield long_operation(); + stdout.puts(@"Async$idx:$i\n"); + for(var j = 0; j < step; ++j) yield do_smth(); } } @@ -15,12 +14,15 @@ public class MainLoopKeeper { void start_methods(MainLoop loop) { var mlk = new MainLoopKeeper(loop); - async_method.begin(1, 8, mlk); - async_method.begin(2, 3, mlk); + async_method.begin(1, 8, 1, mlk); + async_method.begin(2, 3, 2, mlk); } void main() { var loop = new MainLoop(); + stdout.puts("main:1\n"); start_methods(loop); + stdout.puts("main:2\n"); loop.run(); + stdout.puts("main:3\n"); } diff --git a/vala/threads/async_idle.vala b/vala/threads/async_idle.vala new file mode 100644 index 0000000..2ce621f --- /dev/null +++ b/vala/threads/async_idle.vala @@ -0,0 +1,19 @@ +class Test.Async : GLib.Object { + public async string say(string sentence) { + GLib.Idle.add(this.say.callback); // Useful in background threads + yield; // (yield called in the parent(main) thread). + return sentence; + } + public static int main(string[] args) { + Test.Async myasync = new Test.Async(); + GLib.MainLoop mainloop = new GLib.MainLoop(); + myasync.say.begin("helloworld", + (obj, res) => { + string sentence = myasync.say.end(res); + print("%s\n", sentence); + mainloop.quit(); + }); + mainloop.run(); + return 0; + } +} diff --git a/vala/threads/async_idle_bg_thread.vala b/vala/threads/async_idle_bg_thread.vala new file mode 100644 index 0000000..92b033b --- /dev/null +++ b/vala/threads/async_idle_bg_thread.vala @@ -0,0 +1,28 @@ +async double async_method() { + SourceFunc callback = async_method.callback; + + double result = 0; + + ThreadFunc run = () => { + stdout.puts("Thread is running!\n"); + result = 3.14; + stdout.puts("Thread stopped!\n"); + Idle.add((owned)callback); + return null; + }; + + new Thread("debugging thread name", run); + yield; + + return result; +} +void main() { + MainLoop mainloop = new GLib.MainLoop(); + async_method.begin((obj,res) => { + var result = async_method.end(res); + stdout.puts(@"async_method.callback()\nResult = $result\n"); + mainloop.quit(); + } + ); + mainloop.run(); +}