Advertisement
Guest User

Fixed Async Fibonacci Vala

a guest
Feb 20th, 2016
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Vala 2.01 KB | None | 0 0
  1. using Gtk;
  2.  
  3. public long fibonacci (int n)
  4. {
  5.     if (n < 2) {
  6.         return n;
  7.       } else {
  8.         return (fibonacci(n - 1) + fibonacci(n - 2));
  9.     }
  10. }
  11.  
  12. /*long process of much processing*/
  13. public async long long_process (int val)
  14. {
  15.  
  16.     SourceFunc callback = long_process.callback;
  17.     long number = 0;
  18.  
  19.     ThreadFunc<void*> run = () => {  
  20.         number = fibonacci (val);
  21.         Idle.add((owned) callback);
  22.         return null;
  23.     };
  24.  
  25.     Thread.create<void*>(run, false);
  26.  
  27.     yield;
  28.  
  29.     return number;
  30. }
  31.  
  32. public static int main (string[] args)
  33. {
  34.     Gtk.init (ref args);
  35.  
  36.     var window = new Window ();
  37.     window.title = "Fibonacci GTK+";
  38.     window.set_border_width (12);
  39.     window.set_default_size (70, 70);
  40.     window.set_position (Gtk.WindowPosition.CENTER);
  41.     window.destroy.connect (Gtk.main_quit);
  42.  
  43.     var headerbar = new HeaderBar ();
  44.     var entry = new Entry ();
  45.     var button = new Button.with_label ("Calculate");
  46.     var label = new Label ("Result");
  47.     var box = new Box (Orientation.VERTICAL, 0);
  48.  
  49.     headerbar.title = "Fibonacci GTK+";
  50.     headerbar.show_close_button = true;
  51.  
  52.     box.pack_start (entry, false, true, 0);
  53.     box.pack_start (label, false, true, 12);
  54.     box.pack_start (button, false, true, 0);
  55.  
  56.     window.set_titlebar (headerbar);
  57.  
  58.     window.add (box);
  59.     window.show_all ();
  60.  
  61.     /*** LOGIC ***/
  62.     button.clicked.connect ( ()=> {
  63.  
  64.         /*here it called a long process that freezes the user interface*/
  65.         int val = int.parse(entry.get_text());
  66.  
  67.         var loop = new MainLoop();
  68.         long_process.begin(val, (obj, res) => {
  69.                 try {
  70.                     double result = long_process.end(res);
  71.                     label.set_label(result.to_string ());
  72.                 } catch (ThreadError e) {
  73.                     string msg = e.message;
  74.                     stderr.printf(@"Thread error: $msg\n");
  75.                 }
  76.                 loop.quit();
  77.             });
  78.         loop.run();
  79.     });    
  80.  
  81.  
  82.     Gtk.main ();
  83.     return 0;
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement