GLib Reference Manual
<<< Previous Page | Home | Up | Next Page >>>

# The Main Event Loop

## Name

The Main Event Loop -- manages all available sources of events.

## Synopsis

    #include <glib.h>

    struct      GMainLoop;
    GMainLoop*  g_main_new                      (gboolean is_running);
    void        g_main_destroy                  (GMainLoop *loop);
    void        g_main_run                      (GMainLoop *loop);
    gboolean    g_main_is_running               (GMainLoop *loop);
    gboolean    g_main_pending                  (void);
    gboolean    g_main_iteration                (gboolean may_block);
    void        g_main_quit                     (GMainLoop *loop);

    #define     G_PRIORITY_HIGH
    #define     G_PRIORITY_DEFAULT
    #define     G_PRIORITY_HIGH_IDLE
    #define     G_PRIORITY_DEFAULT_IDLE
    #define     G_PRIORITY_LOW

    guint       g_timeout_add                   (guint interval,
                                                 GSourceFunc function,
                                                 gpointer data);
    guint       g_timeout_add_full              (gint priority,
                                                 guint interval,
                                                 GSourceFunc function,
                                                 gpointer data,
                                                 GDestroyNotify notify);
    gboolean    (*GSourceFunc)                  (gpointer data);

    guint       g_idle_add                      (GSourceFunc function,
                                                 gpointer data);
    guint       g_idle_add_full                 (gint priority,
                                                 GSourceFunc function,
                                                 gpointer data,
                                                 GDestroyNotify destroy);
    gboolean    g_idle_remove_by_data           (gpointer data);

    void        g_main_add_poll                 (GPollFD *fd,
                                                 gint priority);
    struct      GPollFD;
    void        g_main_remove_poll              (GPollFD *fd);

    void        g_main_set_poll_func            (GPollFunc func);
    gint        (*GPollFunc)                    (GPollFD *ufds,
                                                 guint nfsd,
                                                 gint timeout);

    guint       g_source_add                    (gint priority,
                                                 gboolean can_recurse,
                                                 GSourceFuncs *funcs,
                                                 gpointer source_data,
                                                 gpointer user_data,
                                                 GDestroyNotify notify);
    struct      GSourceFuncs;
    gboolean    g_source_remove                 (guint tag);
    gboolean    g_source_remove_by_funcs_user_data
                                                (GSourceFuncs *funcs,
                                                 gpointer user_data);
    gboolean    g_source_remove_by_source_data  (gpointer source_data);
    gboolean    g_source_remove_by_user_data    (gpointer user_data);

## Description

The main event loop manages all the available sources of events for GLib and GTK+ applications. These events can come from any number of different types of sources such as file descriptors (plain files, pipes or sockets) and timeouts. New types of event sources can also be added using g_source_add().

Each event source is assigned a priority. The default priority, G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities. Values greater than 0 denote lower priorities. Events from high priority sources are always processed before events from lower priority sources.

Idle functions can also be added, and assigned a priority. These will be run whenever no events with a higher priority are ready to be processed.

The GMainLoop data type represents a main event loop. A GMainLoop is created with g_main_new(). After adding the initial event sources, g_main_run() is called. This continuously checks for new events from each of the event sources and dispatches them. Finally, the processing of an event from one of the sources leads to a call to g_main_quit() to exit the main loop, and g_main_run() returns.

It is possible to create new instances of GMainLoop recursively. This is often used in GTK+ applications when showing modal dialog boxes. However, all event sources are global; they are not tied to a particular GMainLoop.

GTK+ contains wrappers of many of these functions, e.g. gtk_main(), gtk_main_quit(), gtk_events_pending(), gtk_idle_add(), gtk_timeout_add() and gtk_input_add_full(). In a GTK+ application, these wrapper functions should be used instead.

## Details

### struct GMainLoop

    struct GMainLoop;

The GMainLoop struct is an opaque data type representing the main event loop of a GLib or GTK+ application.

### g_main_new ()

    GMainLoop*  g_main_new                      (gboolean is_running);

Creates a new GMainLoop.

`is_running` : | set to TRUE to indicate that the loop is running. This is not very important since calling g_main_run() will set this to TRUE anyway.
Returns : | a new GMainLoop.

### g_main_destroy ()

    void        g_main_destroy                  (GMainLoop *loop);

Frees the memory allocated for the GMainLoop.

`loop` : | a GMainLoop.

### g_main_run ()

    void        g_main_run                      (GMainLoop *loop);

Runs a main loop until it stops running, which occurs when g_main_quit() is called.

`loop` : | a GMainLoop.

### g_main_is_running ()

    gboolean    g_main_is_running               (GMainLoop *loop);

Returns TRUE if the main loop is running.

`loop` : | a GMainLoop.
Returns : | TRUE if the main loop is running.

### g_main_pending ()

    gboolean    g_main_pending                  (void);

Returns TRUE if any events are pending (i.e. ready to be processed).

Returns : | TRUE if any events are pending.

### g_main_iteration ()

    gboolean    g_main_iteration                (gboolean may_block);

Runs a single iteration of the main loop. This will check which event sources are ready to be processed, and will process the highest priority event sources which are ready.

`may_block` : | set to TRUE if it should block (i.e. wait) until an event source becomes ready. It will return after an event source has been processed. If set to FALSE it will return immediately if no event source is ready to be processed.
Returns : | TRUE if more events are pending.

### g_main_quit ()

    void        g_main_quit                     (GMainLoop *loop);

Stops the GMainLoop. If g_main_run() was called to run the GMainLoop, it will now return.

`loop` : | a GMainLoop.

### G_PRIORITY_HIGH

    #define G_PRIORITY_HIGH            -100

Use this for high priority event sources. It is not used within GLib or GTK+.

### G_PRIORITY_DEFAULT

    #define G_PRIORITY_DEFAULT          0

Use this for default priority event sources. In GLib this priority is used when adding timeout functions with g_timeout_add(). In GDK this priority is used for events from the X Windows server.

### G_PRIORITY_HIGH_IDLE

    #define G_PRIORITY_HIGH_IDLE        100

Use this for high priority idle functions. GTK+ uses G_PRIORITY_HIGH_IDLE + 10 for resizing operations, and G_PRIORITY_HIGH_IDLE + 20 for redrawing operations. (This is done to ensure that any pending resizes are processed before any pending redraws, so that widgets are not redrawn twice unnecessarily.)

### G_PRIORITY_DEFAULT_IDLE

    #define G_PRIORITY_DEFAULT_IDLE     200

Use this for default priority idle functions. In GLib this priority is used when adding idle functions with g_idle_add().

### G_PRIORITY_LOW

    #define G_PRIORITY_LOW	            300

Use this for very low priority background tasks. It is not used within GLib or GTK+.

### g_timeout_add ()

    guint       g_timeout_add                   (guint interval,
                                                 GSourceFunc function,
                                                 gpointer data);

Sets a function to be called at regular intervals, with the default priority, G_PRIORITY_DEFAULT. The function is called repeatedly until it returns FALSE, at which point the timeout is automatically destroyed and the function will not be called again. The first call to the function will be at the end of the first `interval`.

Note that timeout functions may be delayed, due to the processing of other event sources. Thus they should not be relied on for precise timing. After each call to the timeout function, the time of the next timeout is recalculated based on the current time and the given interval (it does not try to 'catch up' time lost in delays).

`interval` : | the time between calls to `function`, in milliseconds (1/1000ths of a second.)
`function` : | the function to call at each interval.
`data` : | data to pass to `function`.
Returns : | the id of the event source.

### g_timeout_add_full ()

    guint       g_timeout_add_full              (gint priority,
                                                 guint interval,
                                                 GSourceFunc function,
                                                 gpointer data,
                                                 GDestroyNotify notify);

Sets a function to be called at regular intervals, with the given priority. The function is called repeatedly until it returns FALSE, at which point the timeout is automatically destroyed and the function will not be called again. The `notify` function is called when the timeout is destroyed. The first call to the function will be at the end of the first `interval`.

Note that timeout functions may be delayed, due to the processing of other event sources. Thus they should not be relied on for precise timing. After each call to the timeout function, the time of the next timeout is recalculated based on the current time and the given interval (it does not try to 'catch up' time lost in delays).

`priority` : | the priority of the function. See G_PRIORITY_DEFAULT, G_PRIORITY_DEFAULT_IDLE, G_PRIORITY_HIGH, G_PRIORITY_HIGH_IDLE, and G_PRIORITY_LOW.
`interval` : | the time between calls to the function, in milliseconds (1/1000ths of a second.)
`function` : | the function to call at each interval.
`data` : | data to pass to `function` (and `notify`).
`notify` : | the function to call when the timeout is destroyed, or NULL.
Returns : | the id of event source.

### GSourceFunc ()

    gboolean    (*GSourceFunc)                  (gpointer data);

Specifies the type of function passed to g_timeout_add(), g_timeout_add_full(), g_idle_add(), and g_idle_add_full().

`data` : | data passed to the function, set when the source was created with one of the above functions.
Returns : | it should return FALSE if the source should be removed.

### g_idle_add ()

    guint       g_idle_add                      (GSourceFunc function,
                                                 gpointer data);

Adds a function to be called whenever there are no higher priority events pending. The function is given the default idle priority, G_PRIORITY_DEFAULT_IDLE. If the function returns FALSE it is automatically removed from the list of event sources and will not be called again.

`function` : | the function to call.
`data` : | data to pass to the function.
Returns : | the id of the event source.

### g_idle_add_full ()

    guint       g_idle_add_full                 (gint priority,
                                                 GSourceFunc function,
                                                 gpointer data,
                                                 GDestroyNotify destroy);

Adds a function to be called whenever there are no higher priority events pending. If the function returns FALSE it is automatically removed from the list of event sources and will not be called again.

`priority` : | the priority of the idle function, which should be somewhere around G_PRIORITY_DEFAULT_IDLE and G_PRIORITY_HIGH_IDLE.
`function` : | the function to call.
`data` : | data to pass to the function.
`destroy` : | the function to call when the timeout is destroyed, or NULL.
Returns : | the id of the event source.

### g_idle_remove_by_data ()

    gboolean    g_idle_remove_by_data           (gpointer data);

Removes the idle function with the given data.

`data` : | the data which is passed to the idle function.
Returns : | TRUE if the idle function was found.

### g_main_add_poll ()

    void        g_main_add_poll                 (GPollFD *fd,
                                                 gint priority);

Adds a file descriptor to be polled. This is usually combined with g_source_add() to add an event source. The event source's check function will typically test the revents field in the GPollFD struct and return TRUE if events need to be processed.

`fd` : | a GPollFD, which is a file descriptor together with a bitwise combination of GIOCondition flags determining which events to poll for.
`priority` : | the priority of the poll, which should be the same as the priority used for g_source_add() to ensure that the file descriptor is polled whenever the results may be needed. See G_PRIORITY_DEFAULT, G_PRIORITY_DEFAULT_IDLE, G_PRIORITY_HIGH, G_PRIORITY_HIGH_IDLE, and G_PRIORITY_LOW.

### struct GPollFD

    struct GPollFD
    {
      gint		fd;
      gushort 	events;
      gushort 	revents;
    };

gint fd; | the file descriptor to poll (or a HANDLE on Win32 platforms).
gushort events; | a bitwise combination of flags from GIOCondition, specifying which events should be polled for. Typically for reading from a file descriptor you would use `G_IO_IN` | `G_IO_HUP` | `G_IO_ERR`, and for writing you would use `G_IO_OUT` | `G_IO_ERR`.
gushort revents; | a bitwise combination of flags from GIOCondition, returned from the poll() function to indicate which events occurred.

### g_main_remove_poll ()

    void        g_main_remove_poll              (GPollFD *fd);

Removes a file descriptor from the list being polled.

`fd` : | the GPollFD to remove.

### g_main_set_poll_func ()

    void        g_main_set_poll_func            (GPollFunc func);

Sets the function to use to handle polling of file descriptors. It will be used instead of the `poll()` system call (or GLib's replacement function, which is used where `poll()` isn't available).

This function could possibly be used to integrate the GLib event loop with an external event loop.

`func` : | the function to call to poll all file descriptors.

### GPollFunc ()

    gint        (*GPollFunc)                    (GPollFD *ufds,
                                                 guint nfsd,
                                                 gint timeout);

Specifies the type of function passed to g_main_set_poll_func(). The semantics of the function should match those of the `poll()` system call.

`ufds` : | an array of GPollFD elements.
`nfsd` : | the number of elements in `ufds`.
`timeout` : | the maximum time to wait for an event of the file descriptors.
Returns : | the number of GPollFD elements which have events or errors reported, or -1 if an error occurred.

### g_source_add ()

    guint       g_source_add                    (gint priority,
                                                 gboolean can_recurse,
                                                 GSourceFuncs *funcs,
                                                 gpointer source_data,
                                                 gpointer user_data,
                                                 GDestroyNotify notify);

Adds an event source to the main loop.

`priority` : | the priority of the event source. See G_PRIORITY_DEFAULT, G_PRIORITY_DEFAULT_IDLE, G_PRIORITY_HIGH, G_PRIORITY_HIGH_IDLE, and G_PRIORITY_LOW.
`can_recurse` : | if it is safe to call the source functions recursively.
`funcs` : | the functions to handle the source.
`source_data` : | data specific to the type of event source.
`user_data` : | user data which will be passed to the user function handling the source.
`notify` : | the function to call when the source is destroyed.
Returns : | the id of the event source.

### struct GSourceFuncs

    struct GSourceFuncs
    {
      gboolean (*prepare)  (gpointer  source_data,
    			GTimeVal *current_time,
    			gint     *timeout,
    			gpointer  user_data);
      gboolean (*check)    (gpointer  source_data,
    			GTimeVal *current_time,
    			gpointer  user_data);
      gboolean (*dispatch) (gpointer  source_data,
    			GTimeVal *current_time,
    			gpointer  user_data);
      GDestroyNotify destroy;
    };

The GSourceFuncs struct contains a table of functions used to handle event sources in a generic manner.

prepare | Called before all the file descriptors are polled. If the source can determine that it is ready here (without waiting for the results of the poll() call) it should return TRUE. It can also return a `timeout` value which should be the maximum timeout (in milliseconds) which should be passed to the poll() call. The actual timeout used will be -1 if all sources returned -1, or it will be the minimum of all the `timeout` values returned which were >= 0.
check | Called after all the file descriptors are polled. The source should return TRUE if it is ready to be processed. Note that some time may have passed since the previous prepare function was called, so the source should be checked again here.
dispatch | Called to process the event source, after it has returned TRUE in either its `prepare` or its `check` function.
destroy | Called when the source is destroyed. It will be called with the user data parameter passed to the g_source_add() and related functions.

For idle sources, the prepare and check functions always return TRUE to indicate that the source is always ready to be processed. The prepare function also returns a timeout value of 0 to ensure that the poll() call doesn't block (since that would be time wasted which could have been spent running the idle function).

For timeout sources, the prepare and check functions both return TRUE if the timeout interval has expired. The prepare function also returns a timeout value to ensure that the poll() call doesn't block too long and miss the next timeout.

For file descriptor sources, the prepare function typically returns FALSE, since it must wait until poll() has been called before it knows whether any events need to be processed. It sets the returned timeout to -1 to indicate that it doesn't mind how long the poll() call blocks. In the check function, it tests the results of the poll() call to see if the required condition has been met, and returns TRUE if so.

### g_source_remove ()

    gboolean    g_source_remove                 (guint tag);

Removes the event source with the given id. The id is returned when the source is created, either directly with g_source_add(), or indirectly with g_idle_add(), g_idle_add_full(), g_timeout_add() and g_timeout_add_full().

`tag` : | the id of the event source to remove.
Returns : | TRUE if the source was found and removed.

### g_source_remove_by_funcs_user_data ()

    gboolean    g_source_remove_by_funcs_user_data
                                                (GSourceFuncs *funcs,
                                                 gpointer user_data);

Removes the first event source found with the given GSourceFuncs and user data.

Event sources are sorted with the highest priority first. Sources with equal priority are stored in the order in which they were added.

`funcs` : | the GSourceFuncs of the source to remove.
`user_data` : | the user data of the source to remove.
Returns : | TRUE if an event source was found and removed.

### g_source_remove_by_source_data ()

    gboolean    g_source_remove_by_source_data  (gpointer source_data);

Removes the first event source found with the given source data.

Event sources are sorted with the highest priority first. Sources with equal priority are stored in the order in which they were added.

`source_data` : | the source data, which contains information specific to the type of source.
Returns : | TRUE if an event source was found and removed.

### g_source_remove_by_user_data ()

    gboolean    g_source_remove_by_user_data    (gpointer user_data);

Removes the first event source found with the given user data.

Event sources are sorted with the highest priority first. Sources with equal priority are stored in the order in which they were added.

`user_data` : | the user data of the source to remove.
Returns : | TRUE if an event source was found and removed.

<<< Previous Page | Home | Up | Next Page >>>
GLib Core Application Support | Threads