GLib.Thread.vala 1001 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. extern int get_ret_code ();
  2. public class MyThread : Object {
  3. public int x_times { get; private set; }
  4. public MyThread (int times) {
  5. this.x_times = times;
  6. }
  7. public int run () {
  8. for (int i = 0; i < this.x_times; i++) {
  9. stdout.printf ("ping! %d/%d\n", i + 1, this.x_times);
  10. Thread.usleep (10000);
  11. }
  12. // return & exit have the same effect
  13. Thread.exit (get_ret_code ());
  14. return 43;
  15. }
  16. }
  17. public static int main (string[] args) {
  18. // Check whether threads are supported:
  19. if (Thread.supported () == false) {
  20. stderr.printf ("Threads are not supported!\n");
  21. return -1;
  22. }
  23. try {
  24. // Start a thread:
  25. MyThread my_thread = new MyThread (10);
  26. Thread<int> thread = new Thread<int>.try ("My fst. thread", my_thread.run);
  27. // Wait until thread finishes:
  28. int result = thread.join ();
  29. // Output: `Thread stopped! Return value: 42`
  30. stdout.printf ("Thread stopped! Return value: %d\n", result);
  31. } catch (Error e) {
  32. stdout.printf ("Error: %s\n", e.message);
  33. }
  34. return 0;
  35. }