Share Pastebin
Guest
Public paste!

Lucas Hermann Negri

By: a guest | Jun 13th, 2009 | Syntax: C | Size: 1.19 KB | Hits: 141 | Expires: Never
Copy text to clipboard
  1. #include <glib/gthread.h>
  2.  
  3. /* we need to eat some cpu time! */
  4. gint fib(gint n)
  5. {
  6.         if(n == 1 || n == 2) return 1;
  7.         return fib(n - 1) + fib(n - 2);
  8. }
  9.  
  10. /* our background task caller */
  11. gpointer bg_task(gpointer data)
  12. {
  13.         gint res = fib( GPOINTER_TO_INT(data) );
  14.         return GINT_TO_POINTER(res);
  15. }
  16.  
  17. int main(int argc, char* argv[])
  18. {
  19.         g_thread_init(NULL);
  20.        
  21.         GError *error1 = NULL, *error2 = NULL, *error3 = NULL, *error4 = NULL;
  22.        
  23.         g_print("initializing tasks...\n");
  24.         GThread* t1 = g_thread_create(bg_task, GINT_TO_POINTER(40), TRUE, &error1);
  25.         GThread* t2 = g_thread_create(bg_task, GINT_TO_POINTER(42), TRUE, &error2);
  26.         GThread* t3 = g_thread_create(bg_task, GINT_TO_POINTER(5), TRUE, &error3);
  27.         GThread* t4 = g_thread_create(bg_task, GINT_TO_POINTER(10), TRUE, &error4);
  28.        
  29.         if(error1 || error2 || error3 || error4)
  30.         {
  31.                 g_print("Error!");
  32.                 return 1;
  33.         }
  34.        
  35.         g_print("waiting for the tasks...\n");
  36.         gint res1 = GPOINTER_TO_INT(g_thread_join(t1));
  37.         gint res2 = GPOINTER_TO_INT(g_thread_join(t2));
  38.         gint res3 = GPOINTER_TO_INT(g_thread_join(t3));
  39.         gint res4 = GPOINTER_TO_INT(g_thread_join(t4));
  40.        
  41.         g_print("results: %d, %d, %d, %d\n", res1, res2, res3, res4);
  42.        
  43.         return 0;
  44. }