Creating a new GSource in GLib

c, glib

Solution

From the source definition it looks like you can attach a GSource only to one `GMainContext`

struct _GSource
{
  /*< private >*/
  gpointer callback_data;
  GSourceCallbackFuncs *callback_funcs;

  const GSourceFuncs *source_funcs;
  guint ref_count;

  GMainContext *context;    // <<<<<

  gint priority;
  guint flags;
  guint source_id;

  GSList *poll_fds;

  GSource *prev;
  GSource *next;

  char    *name;

  GSourcePrivate *priv;
};

Have a look at

static guint
g_source_attach_unlocked (GSource      *source,
                      GMainContext *context,
                      gboolean      do_wakeup)

which will tell you that only the associated `GMainContext` will be woken.

Example of derived `GSource` usage: https://github.com/chergert/iris/blob/master/iris/iris-gsource.c

Problem

I'm trying to understand what it means when I call `g_source_new`. The latest API documentation (at this time its 2.38.2) on the call just says: Creates a new GSource structure. The size is specified to allow creating structures derived from GSource that contain additional data. The size passed in must be at least sizeof (GSource). I'm trying to understand if invoking this API means that I'm instantiating a new instance of my `GSource` or if it's intended as a registration of a new `GSource` type. The underlying question is this: Am I allowed to create one new `GSource` using `g_source_new` and then apply that to any number of contexts (via `g_source_attach`)? Or must I utilize both functions even when attempting to apply the same `GSource` I've defined to multiple contexts?

Original source