Re: Removing widgets in the main loop from another thread



On Thu, 26 Feb 2009 13:55:20 +0100
Robert Gründler <doobre gmail com> wrote:
> Hi all,
> 
> i'm trying to add/remove widgets dynamically to a gtk::window from a 
> separate thread. The classes i'm creating hold a singleton to the
> object that runs the main loop in the separate thread, and i
> communicate with the main loop thread using the Glib::Dispatcher
> class.
> 
> The widgets will be created in the constructor of my classes, and 
> removed from the window in the destructor. But with the destructor
> i'm having a slight problem, as the function that actually calls the 
> removeWidget method on the main loop is called asynchroniosly by
> the dispatcher, therefore, the objects which should get removed will 
> eventually be already destroyed when the main loop receives the
> signal.
> 
> here's some code how i'm implementing it right now:
> 
> remove_dispatcher().connect(sigc::mem_fun(*this, 
> &myObject::myRemoveFunction));
> 
> ...
> 
> void myObject::myRemoveFunction() { // <-- might be called by the 
> dispatcher when the object doesn't exist anymore
> 
>   mainProxy->removeWidget(this);
> 
> }
> 
> myObject::~myObject() {
>   remove_dispatcher();  <-- calls myRemoveFunction()
> }
> 
> 
> My question now is, is there any way to make a glib::dispatcher wait 
> until it actually has emitted the signal until it returns ?
> This way i could ensure the object still exists when the main loop is 
> called.

Because your arrangement doesn't on the face of it make sense, there
is probably more to it than at first appears.  I therefore just make
three points which may or may not be relevant to your question:

1. You cannot (without great difficulty) have different Gtk::Window
objects created and/or destroyed in different threads.  If it is
possible at all, you will need to use the GDK global thread lock, which
makes the use of Glib::Dispatcher redundant.  You may also need to have
two main loop objects, one for each thread (from your description it is
impossible to say).

2. If you set gtkmm containers (including Gtk::Window) to manage their
contents then the destructor of the Gtk::Window object will
automatically deal with its contents without you needing to do
anything else.

3. You don't need to worry about an object ceasing to exist before a
Glib::Dispatcher emission is executed via the main loop on one of its
non-static methods if you derive the object from sigc::trackable.  The
invocation in that case would be a no-op.  (Note however that
sigc::trackable is not thread safe, so all slot creation and
destruction on non-static methods of an object derived from
sigc::trackable must occur in the thread which manages the lifetime of
the object, which means amongst other things that you should not call
Glib::Thread::create() on any non-static methods of the object).

Chris



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