MainContext#
- class MainContext(**kwargs)#
The GMainContext
struct is an opaque data
type representing a set of sources to be handled in a main loop.
Constructors#
- class MainContext
- classmethod new() MainContext #
Creates a new
MainContext
structure.
- classmethod new_with_flags(flags: MainContextFlags) MainContext #
Creates a new
MainContext
structure.Added in version 2.72.
- Parameters:
flags – a bitwise-OR combination of
MainContextFlags
flags that can only be set at creation time.
Methods#
- class MainContext
- acquire() bool #
Tries to become the owner of the specified context. If some other thread is the owner of the context, returns
False
immediately. Ownership is properly recursive: the owner can require ownership again and will release ownership whenrelease
is called as many times asacquire
.You must be the owner of a context before you can call
prepare
,query
,check
,dispatch
,release
.Since 2.76
context
can beNone
to use the global-default main context.
- add_poll(fd: PollFD, priority: int) None #
Adds a file descriptor to the set of file descriptors polled for this context. This will very seldom be used directly. Instead a typical event source will use
g_source_add_unix_fd
instead.
- check(max_priority: int, fds: list[PollFD]) bool #
Passes the results of polling back to the main loop. You should be careful to pass
fds
and its lengthn_fds
as received fromquery
, as this functions relies on assumptions on howfds
is filled.You must have successfully acquired the context with
acquire
before you may call this function.Since 2.76
context
can beNone
to use the global-default main context.
- classmethod default() MainContext #
Returns the global-default main context. This is the main context used for main loop functions when a main loop is not explicitly specified, and corresponds to the “main” main loop. See also
get_thread_default
.
- dispatch() None #
Dispatches all pending sources.
You must have successfully acquired the context with
acquire
before you may call this function.Since 2.76
context
can beNone
to use the global-default main context.
- find_source_by_funcs_user_data(funcs: SourceFuncs, user_data: Any = None) Source #
Finds a source with the given source functions and user data. If multiple sources exist with the same source function and user data, the first one found will be returned.
- Parameters:
funcs – the
source_funcs
passed tonew
.user_data – the user data from the callback.
- find_source_by_id(source_id: int) Source #
Finds a
Source
given a pair of context and ID.It is a programmer error to attempt to look up a non-existent source.
More specifically: source IDs can be reissued after a source has been destroyed and therefore it is never valid to use this function with a source ID which may have already been removed. An example is when scheduling an idle to run in another thread with
idle_add
: the idle may already have run and been removed by the time this function is called on its (now invalid) source ID. This source ID may have been reissued, leading to the operation being performed against the wrong source.- Parameters:
source_id – the source ID, as returned by
get_id
.
- find_source_by_user_data(user_data: Any = None) Source #
Finds a source with the given user data for the callback. If multiple sources exist with the same user data, the first one found will be returned.
- Parameters:
user_data – the user_data for the callback.
- classmethod get_thread_default() MainContext | None #
Gets the thread-default
MainContext
for this thread. Asynchronous operations that want to be able to be run in contexts other than the default one should call this method orref_thread_default
to get aMainContext
to add theirSource
s to. (Note that even in single-threaded programs applications may sometimes want to temporarily push a non-default context, so it is not safe to assume that this will always returnNone
if you are running in the default thread.)If you need to hold a reference on the context, use
ref_thread_default
instead.Added in version 2.22.
- invoke_full(priority: int, function: Callable[[Any], bool], data: Any = None) None #
Invokes a function in such a way that
context
is owned during the invocation offunction
.This function is the same as
invoke
except that it lets you specify the priority in casefunction
ends up being scheduled as an idle and also lets you give aDestroyNotify
fordata
.notify
should not assume that it is called from any particular thread or with any particular context acquired.Added in version 2.28.
- Parameters:
priority – the priority at which to run
function
function – function to call
data – data to pass to
function
- is_owner() bool #
Determines whether this thread holds the (recursive) ownership of this
MainContext
. This is useful to know before waiting on another thread that may be blocking to get ownership ofcontext
.Added in version 2.10.
- iteration(may_block=True)#
Runs a single iteration for the given main loop. This involves checking to see if any event sources are ready to be processed, then if no events sources are ready and
may_block
isTrue
, waiting for a source to become ready, then dispatching the highest priority events sources that are ready. Otherwise, ifmay_block
isFalse
sources are not waited to become ready, only those highest priority events sources will be dispatched (if any), that are ready at this given moment without further waiting.Note that even when
may_block
isTrue
, it is still possible foriteration
to returnFalse
, since the wait may be interrupted for other reasons than an event source becoming ready.- Parameters:
may_block – whether the call may block.
- pop_thread_default() None #
Pops
context
off the thread-default context stack (verifying that it was on the top of the stack).Added in version 2.22.
- prepare() tuple[bool, int] #
Prepares to poll sources within a main loop. The resulting information for polling is determined by calling
query
.You must have successfully acquired the context with
acquire
before you may call this function.
- push_thread_default() None #
Acquires
context
and sets it as the thread-default context for the current thread. This will cause certain asynchronous operations (such as most [gio][gio]-based I/O) which are started in this thread to run undercontext
and deliver their results to its main loop, rather than running under the global default main context in the main thread. Note that calling this function changes the context returned byget_thread_default
, not the one returned bydefault
, so it does not affect the context used by functions likeidle_add
.Normally you would call this function shortly after creating a new thread, passing it a
MainContext
which will be run by aMainLoop
in that thread, to set a new default context for all async operations in that thread. In this case you may not need to ever callpop_thread_default
, assuming you want the newMainContext
to be the default for the whole lifecycle of the thread.If you don’t have control over how the new thread was created (e.g. in the new thread isn’t newly created, or if the thread life cycle is managed by a
ThreadPool
), it is always suggested to wrap the logic that needs to use the newMainContext
inside apush_thread_default
/pop_thread_default
pair, otherwise threads that are re-used will end up never explicitly releasing theMainContext
reference they hold.In some cases you may want to schedule a single operation in a non-default context, or temporarily use a non-default context in the main thread. In that case, you can wrap the call to the asynchronous operation inside a
push_thread_default
/pop_thread_default
pair, but it is up to you to ensure that no other asynchronous operations accidentally get started while the non-default context is active.Beware that libraries that predate this function may not correctly handle being used from a thread with a thread-default context. Eg, see g_file_supports_thread_contexts().
Added in version 2.22.
- query(max_priority: int) tuple[int, int, list[PollFD]] #
Determines information necessary to poll this main loop. You should be careful to pass the resulting
fds
array and its lengthn_fds
as is when callingcheck
, as this function relies on assumptions made when the array is filled.You must have successfully acquired the context with
acquire
before you may call this function.- Parameters:
max_priority – maximum priority source to check
- release() None #
Releases ownership of a context previously acquired by this thread with
acquire
. If the context was acquired multiple times, the ownership will be released only whenrelease
is called as many times as it was acquired.You must have successfully acquired the context with
acquire
before you may call this function.
- remove_poll(fd: PollFD) None #
Removes file descriptor from the set of file descriptors to be polled for a particular context.
- wait(cond: Cond, mutex: Mutex) bool #
Tries to become the owner of the specified context, as with
acquire
. But if another thread is the owner, atomically dropmutex
and wait oncond
until that owner releases ownership or untilcond
is signaled, then try again (once) to become the owner.Deprecated since version 2.58:
- Use
is_owner
and separate locking instead.
- Parameters:
cond – a condition variable
mutex – a mutex, currently held
- Use
- wakeup() None #
If
context
is currently blocking initeration
waiting for a source to become ready, cause it to stop blocking and return. Otherwise, cause the next invocation ofiteration
to return without blocking.This API is useful for low-level control over
MainContext
; for example, integrating it with main loop implementations such asMainLoop
.Another related use for this function is when implementing a main loop with a termination condition, computed from multiple threads:
#define NUM_TASKS 10 static gint tasks_remaining = NUM_TASKS; // (atomic) ... while (g_atomic_int_get (&tasks_remaining) != 0) g_main_context_iteration (NULL, TRUE);
Then in a thread:
perform_work(); if (g_atomic_int_dec_and_test (&tasks_remaining)) g_main_context_wakeup (NULL);