Marwan
Marwan

Reputation: 149

GTK+ Thread safety

I'm trying to use threads to manage several things in GTK+, however, as soon as I try to use any GUI function in the new thread, it locks up the GUI and this makes sense since GTK+ is not thread safe. Is there anyway around this?

Here's my code:

int main(int argc, char *argv[])
{   

 GError *error = NULL;

/* init threads */  
g_thread_init(NULL);
gdk_threads_init();

/* init gtk */
gtk_init(&argc, &argv);

....

//Multithreaded functions
g_thread_create(argument_thread, (gpointer)label7, FALSE, &error );

gdk_threads_enter();
gtk_main();
gdk_threads_leave();
return 0;
}

void *argument_thread(void *args)
{
    while(1)
    {
    gdk_threads_enter();
    gtk_entry_set_text(entry2,"random stuff");
    gdk_threads_leave();

    }
}

Upvotes: 1

Views: 2964

Answers (2)

Fabio Di Matteo
Fabio Di Matteo

Reputation: 45

I have resolved the problem using g_timeout e gthread:http://www.freemedialab.org/wiki/doku.php?id=programmazione:gtk:gtk_e_i_thread

Basically I use 3 functions, one that launches the thread, one that does the job without manipulating widgets (thread) and a third type that serves as a timeout timer checking every n seconds certain values ​​written by the thread and updates the ' graphic interface.

Or you can use "g_idle_add" : http://www.freemedialab.org/wiki/doku.php?id=programmazione:gtk:gtk_e_i_thread#versione_con_g_idle_add

gdk_threads_enter() and gdk_threads_leave() are deprecated from 3.6 version of Gtk.

Upvotes: -1

Pragmateek
Pragmateek

Reputation: 13374

Not sure if this could be an issue (don't know GTK) but maybe there is a race condition if the thread acquires the lock before the gtk_main has started.

Then you could try:

gdk_threads_enter();

//Multithreaded functions
g_thread_create(argument_thread, (gpointer)label7, FALSE, &error );

gtk_main();
gdk_threads_leave();

Moreover you should temporize your loop:

void *argument_thread(void *args)
{
    while(1)
    {
        gdk_threads_enter();
        gtk_entry_set_text(entry2,"random stuff");
        gdk_threads_leave();

        sleep(10);
    }
}

Upvotes: 3

Related Questions