Re: Forcing a G Timeout to be handled by a specific thread

Hi Andrew,

    I wrote some Glib programming example in the past, this code is about 
creating GMainContext, GMainLoop and GSources (that g_timeout_add() function
and friends did) into separate thread, hope this will be usefull for you.

#include <glib.h>

typedef struct 
  GMainLoop *loop;
  guint n_run;
} LoopInfo;

gboolean callback (LoopInfo *info)
  info->n_run -= 1;

  g_print ("loop %p n_run: %u\n", info->loop, info->n_run);

  if (info->n_run <= 0)
      g_main_loop_quit (info->loop);
      g_print ("loop %p quit\n", info->loop);
      return FALSE;

  return TRUE;

gpointer *thread1 (gpointer *data)
  GMainLoop *loop = g_main_loop_new (NULL, FALSE);
  GSource *source = g_timeout_source_new (2250);
  LoopInfo info = { .loop = loop, .n_run = 3 };

  g_source_set_callback (source, (GSourceFunc) callback, &info, NULL);
  g_source_attach (source, NULL);
  g_print ("loop %p run\n", loop);
  g_main_loop_run (loop);

  return NULL;

gint main(void)
  g_thread_init (NULL);
  GThread *thread = g_thread_create ((GThreadFunc) thread1, NULL, TRUE, NULL);

  GMainContext *ctx = g_main_context_new ();
  GMainLoop *loop = g_main_loop_new (ctx, FALSE);
  GSource *source = g_timeout_source_new_seconds (1);
  LoopInfo info = { .loop = loop, .n_run = 5 };

  g_source_set_callback (source, (GSourceFunc) callback, &info, NULL);
  g_source_attach (source, ctx);
  g_print ("loop %p run\n", loop);
  g_main_loop_run (loop);
  g_thread_join (thread);

  return 0;

--- a j w me com wrote:

From: Andrew Wood <a j w me com>
To: gtk-app-devel-list <gtk-app-devel-list gnome org>
Subject: Forcing a G Timeout to be handled by a specific thread
Date: Wed, 05 Oct 2011 14:00:40 +0100

Is there a way to ensure a timeout callback set with g_timeout_add is 
always executed by a specific pthread?

gtk-app-devel-list mailing list
gtk-app-devel-list gnome org

Listen to KNAC, Hit the Home page and Tune In Live! --->

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