Class MainContext
- All Implemented Interfaces:
Proxy
GMainContext struct is an opaque data
type representing a set of sources to be handled in a main loop.-
Constructor Summary
ConstructorsConstructorDescriptionCreates a newGLib.MainContextstructure.MainContext(MemorySegment address) Create a MainContext proxy instance for the provided memory address. -
Method Summary
Modifier and TypeMethodDescriptionbooleanacquire()Tries to become the owner of the specified context.voidAdds a file descriptor to the set of file descriptors polled for this context.static MainContextdefault_()Returns the global-default main context.voiddispatch()Dispatches all pending sources.@Nullable SourcefindSourceByFuncsUserData(SourceFuncs funcs, @Nullable MemorySegment userData) Finds a source with the given source functions and user data.findSourceById(int sourceId) Finds aGLib.Sourcegiven a pair of context and ID.@Nullable SourcefindSourceByUserData(@Nullable MemorySegment userData) Finds a source with the given user data for the callback.@Nullable PollFuncGets the poll function set bysetPollFunc(org.gnome.glib.PollFunc).static @Nullable MainContextGets the thread-default main context for this thread.static @Nullable TypegetType()Get the GType of the MainContext classvoidinvoke(@Nullable SourceFunc function) Invokes a function in such a way that this MainContext is owned during the invocation offunction.voidinvokeFull(int priority, @Nullable SourceFunc function) Invokes a function in such a way that this MainContext is owned during the invocation offunction.booleanisOwner()Determines whether this thread holds the (recursive) ownership of thisGLib.MainContext.booleaniteration(boolean mayBlock) Runs a single iteration for the given main loop.booleanpending()Checks if any sources have pending events for the given context.voidPops this MainContext off the thread-default context stack (verifying that it was on the top of the stack).booleanPrepares to poll sources within a main loop.static voidpusherFree(MainContextPusher pusher) Poppusher’smain context as the thread default main context.Push this MainContext as the new thread-default main context for the current thread, usingpushThreadDefault(), and return a newGLib.MainContextPusher.voidAcquires this MainContext and sets it as the thread-default context for the current thread.ref()Increases the reference count on aGLib.MainContextobject by one.static MainContextGets a reference to the thread-defaultGLib.MainContextfor this threadvoidrelease()Releases ownership of a context previously acquired by this thread withacquire().voidremovePoll(PollFD fd) Removes file descriptor from the set of file descriptors to be polled for a particular context.voidsetPollFunc(@Nullable PollFunc func) Sets the function to use to handle polling of file descriptors.voidunref()Decreases the reference count on aGLib.MainContextobject by one.booleanDeprecated.voidwakeup()Wake up this MainContext if it’s currently blocking initeration(boolean), causing it to stop blocking.static MainContextwithFlags(Set<MainContextFlags> flags) Creates a newGLib.MainContextstructure.static MainContextwithFlags(MainContextFlags... flags) Creates a newGLib.MainContextstructure.Methods inherited from class org.javagi.base.ProxyInstance
equals, handle, hashCode
-
Constructor Details
-
MainContext
Create a MainContext proxy instance for the provided memory address.- Parameters:
address- the memory address of the native object
-
MainContext
public MainContext()Creates a newGLib.MainContextstructure.
-
-
Method Details
-
getType
-
withFlags
Creates a newGLib.MainContextstructure.- Parameters:
flags- a bitwise-OR combination of flags that can only be set at creation time- Returns:
- the new main context
- Since:
- 2.72
-
withFlags
Creates a newGLib.MainContextstructure.- Parameters:
flags- a bitwise-OR combination of flags that can only be set at creation time- Returns:
- the new main context
- Since:
- 2.72
-
default_
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
getThreadDefault().- Returns:
- the global-default main context.
-
getThreadDefault
Gets the thread-default main context for this thread.Asynchronous operations that want to be able to be run in contexts other than the default one should call this method or
refThreadDefault()to get aGLib.MainContextto add theirGLib.Sources 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 returnNULLif you are running in the default thread.)If you need to hold a reference on the context, use
refThreadDefault()instead.- Returns:
- the thread-default main context, or
NULLif the thread-default context is the global-default main context - Since:
- 2.22
-
pusherFree
Poppusher’smain context as the thread default main context. See g_main_context_pusher_new() for details.This will pop the
GLib.MainContextas the current thread-default main context, but will not callunref()on it.- Parameters:
pusher- aGMainContextPusher- Since:
- 2.64
-
refThreadDefault
Gets a reference to the thread-defaultGLib.MainContextfor this threadThis is the same as
getThreadDefault(), but it also adds a reference to the returned main context withref(). In addition, unlikegetThreadDefault(), if the thread-default context is the global-default context, this will return thatGLib.MainContext(with a ref added to it) rather than returningNULL.- Returns:
- the thread-default main context
- Since:
- 2.32
-
acquire
public boolean acquire()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 when
release()is called as many times asacquire().You must be the owner of a context before you can call
prepare(org.javagi.base.Out<java.lang.Integer>),MainContext#query,MainContext#check,dispatch(),release().Since 2.76 this MainContext can be
NULLto use the global-default main context.- Returns:
- true if this thread is now the owner of
context,false otherwise
-
addPoll
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.- Parameters:
fd- aGLib.PollFDstructure holding information about a file descriptor to watch.priority- the priority for this file descriptor which should be the same as the priority used forSource.attach(org.gnome.glib.MainContext)to ensure that the file descriptor is polled whenever the results may be needed.
-
dispatch
public void dispatch()Dispatches all pending sources.You must have successfully acquired the context with
acquire()before you may call this function.Since 2.76 this MainContext can be
NULLto use the global-default main context. -
findSourceByFuncsUserData
public @Nullable Source findSourceByFuncsUserData(SourceFuncs funcs, @Nullable MemorySegment userData) 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- thesourceFuncspassed toSource(org.gnome.glib.SourceFuncs, int)userData- the user data from the callback- Returns:
- the source, if one was found,
otherwise
NULL
-
findSourceById
Finds aGLib.Sourcegiven 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
GLib.idleAdd(int, org.gnome.glib.SourceFunc): 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:
sourceId- the source ID, as returned bySource.getId()- Returns:
- the source
-
findSourceByUserData
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:
userData- the user_data for the callback- Returns:
- the source, if one was found,
otherwise
NULL
-
getPollFunc
Gets the poll function set bysetPollFunc(org.gnome.glib.PollFunc).- Returns:
- the poll function
-
invoke
Invokes a function in such a way that this MainContext is owned during the invocation offunction.If this MainContext is
NULLthen the global-default main context — as returned bydefault_()— is used.If this MainContext is owned by the current thread,
functionis called directly. Otherwise, if this MainContext is the thread-default main context of the current thread andacquire()succeeds, thenfunctionis called andrelease()is called afterwards.In any other case, an idle source is created to call
functionand that source is attached to this MainContext (presumably to be run in another thread). The idle source is attached withGLib.PRIORITY_DEFAULTpriority. If you want a different priority, useinvokeFull(int, org.gnome.glib.SourceFunc).Note that, as with normal idle functions,
functionshould probably returnGLib.SOURCE_REMOVE. If it returnsGLib.SOURCE_CONTINUE, it will be continuously run in a loop (and may prevent this call from returning).- Parameters:
function- function to call- Since:
- 2.28
-
invokeFull
Invokes a function in such a way that this MainContext is owned during the invocation offunction.This function is the same as
invoke(org.gnome.glib.SourceFunc)except that it lets you specify the priority in casefunctionends up being scheduled as an idle and also lets you give aGLib.DestroyNotifyfordata.The
notifyfunction should not assume that it is called from any particular thread or with any particular context acquired.- Parameters:
priority- the priority at which to runfunctionfunction- function to call- Since:
- 2.28
-
isOwner
public boolean isOwner()Determines whether this thread holds the (recursive) ownership of thisGLib.MainContext.This is useful to know before waiting on another thread that may be blocking to get ownership of
context.- Returns:
- true if current thread is owner of
context,false otherwise - Since:
- 2.10
-
iteration
public boolean iteration(boolean mayBlock) 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
mayBlockis true, waiting for a source to become ready, then dispatching the highest priority events sources that are ready. Otherwise, ifmayBlockis false, this function does not wait for sources to become ready, and only the highest priority sources which are already ready (if any) will be dispatched.Note that even when
mayBlockis true, it is still possible foriteration(boolean)to return false, since the wait may be interrupted for other reasons than an event source becoming ready.- Parameters:
mayBlock- whether the call may block- Returns:
- true if events were dispatched, false otherwise
-
pending
public boolean pending()Checks if any sources have pending events for the given context.- Returns:
- true if events are pending, false otherwise
-
popThreadDefault
public void popThreadDefault()Pops this MainContext off the thread-default context stack (verifying that it was on the top of the stack).- Since:
- 2.22
-
prepare
Prepares to poll sources within a main loop.The resulting information for polling is determined by calling
MainContext#query.You must have successfully acquired the context with
acquire()before you may call this function.- Parameters:
priority- location to store priority of highest priority source already ready- Returns:
- true if some source is ready to be dispatched prior to polling, false otherwise
-
pushThreadDefault
public void pushThreadDefault()Acquires this MainContext and sets it as the thread-default context for the current thread. This will cause certain asynchronous operations (such as most Gio-based I/O) which are started in this thread to run under this MainContext 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 bygetThreadDefault(), not the one returned bydefault_(), so it does not affect the context used by functions likeGLib.idleAdd(int, org.gnome.glib.SourceFunc).Normally you would call this function shortly after creating a new thread, passing it a
GLib.MainContextwhich will be run by aGLib.MainLoopin that thread, to set a new default context for all async operations in that thread. In this case you may not need to ever callpopThreadDefault(), assuming you want the newGLib.MainContextto 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
GThreadPool), it is always suggested to wrap the logic that needs to use the newGLib.MainContextinside apushThreadDefault()/popThreadDefault()pair, otherwise threads that are re-used will end up never explicitly releasing theGLib.MainContextreference 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
pushThreadDefault()/popThreadDefault()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. For example, see
g_file_supports_thread_contexts().- Since:
- 2.22
-
pusherNew
Push this MainContext as the new thread-default main context for the current thread, usingpushThreadDefault(), and return a newGLib.MainContextPusher. Pop with g_main_context_pusher_free(). UsingpopThreadDefault()on this MainContext while aGLib.MainContextPusherexists for it can lead to undefined behaviour.Using two
GLib.MainContextPushers in the same scope is not allowed, as it leads to an undefined pop order.This is intended to be used with g_autoptr(). Note that g_autoptr() is only available when using GCC or clang, so the following example will only work with those compilers:
typedef struct { ... GMainContext *context; ... } MyObject; static void my_object_do_stuff (MyObject *self) { g_autoptr(GMainContextPusher) pusher = g_main_context_pusher_new (self->context); // Code with main context as the thread default here if (cond) // No need to pop return; // Optionally early pop g_clear_pointer (&pusher, g_main_context_pusher_free); // Code with main context no longer the thread default here }- Returns:
- a
GMainContextPusher - Since:
- 2.64
-
ref
Increases the reference count on aGLib.MainContextobject by one.- Returns:
- the this MainContext that was passed in (since 2.6)
-
release
public void release()Releases ownership of a context previously acquired by this thread withacquire().If the context was acquired multiple times, the ownership will be released only when
release()is called as many times as it was acquired.You must have successfully acquired the context with
acquire()before you may call this function. -
removePoll
Removes file descriptor from the set of file descriptors to be polled for a particular context.- Parameters:
fd- aGLib.PollFDdescriptor previously added withaddPoll(org.gnome.glib.PollFD, int)
-
setPollFunc
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 wherepoll()isn’t available).This function could possibly be used to integrate the GLib event loop with an external event loop.
- Parameters:
func- the function to call to poll all file descriptors
-
unref
public void unref()Decreases the reference count on aGLib.MainContextobject by one. If the result is zero, free the context and free all associated memory. -
wait_
Deprecated.UseisOwner()and separate locking instead.Tries to become the owner of the specified context, and waits oncondif another thread is the owner.This is the same as
acquire(), but if another thread is the owner, atomically dropmutexand wait onconduntil that owner releases ownership or untilcondis signaled, then try again (once) to become the owner.- Parameters:
cond- a condition variablemutex- a mutex, currently held- Returns:
- true if this thread is now the owner of
context,false otherwise
-
wakeup
public void wakeup()Wake up this MainContext if it’s currently blocking initeration(boolean), causing it to stop blocking.The this MainContext could be blocking waiting for a source to become ready. Otherwise, if this MainContext is not currently blocking, this function causes the next invocation of
iteration(boolean)to return without blocking.This API is useful for low-level control over
GLib.MainContext; for example, integrating it with main loop implementations such asGLib.MainLoop.Another related use for this function is when implementing a main loop with a termination condition, computed from multiple threads:
Then in a thread:#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);perform_work (); if (g_atomic_int_dec_and_test (&tasks_remaining)) g_main_context_wakeup (NULL);
-
isOwner()and separate locking instead.