(no subject)



Thanks to all who answered my previous questions.

I have now a question about threads. Suppose I want the following simple
application: a window with only two buttons: START and STOP. When START is
clicked, a thread THR is created, which does some CPU intensive job. STOP
must obviously stop THR. I created the interface with glade, and coded the
threads stuff. The "working" thread (THR) does start when START is
clicked, but then STOP does not respond, and THR keeps running. This is my
first example using threads with gtk, and there are many thing that I
don't understand. For instance, why the gdk_threads_enter()/leave() around
gtk_main()? I saw that in Eric Mouw's example, but I don't quite
understand what I have to lock in my example. It doesn't seem to make a
difference anyway. The buttons are dead until the working thread is done.
Is there any way I can "wake up" the main thread to listen to events once
in a while?


Please see the code below.
Thanks!



/***************************** File main.c ******************************/


#include <gnome.h>

#include "interface.h"
#include "support.h"

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

#ifdef ENABLE_NLS
    bindtextdomain (PACKAGE, PACKAGE_LOCALE_DIR);
    textdomain (PACKAGE);
#endif

    g_thread_init(NULL);
    gnome_init ("pthr", VERSION, argc, argv);

    /*
     * The following code was added by Glade to create one of each
component
     * (except popup menus), just so that you see something after building
     * the project. Delete any components that you don't want shown
initially.
     */
    window1 = create_window1 ();
    gtk_widget_show (window1);

    gdk_threads_enter();
    gtk_main ();
    gdk_threads_leave();

    return 0;
}


/********************************* end main.c ***************************/




/******************************* file callbacks.c **********************/


#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif

#include <gnome.h>
#include <pthread.h>

#include "callbacks.h"
#include "interface.h"
#include "support.h"


pthread_t THR;

// Function executed by THR
void work(void * arg)
{
    int i;

    // Some CPU intensive task
    for(i=0; i<100000; i++)
	printf("%d\n", i);

}



void
on_start_clicked                       (GtkButton       *button,
                                        gpointer         user_data)
{
    if (pthread_create(&THR, NULL, (void *) &work, NULL) != 0){
        printf("Can't create thread\n");
        exit(-1);
    }

    work(NULL);    
}


void
on_stop_clicked                        (GtkButton       *button,
                                        gpointer         user_data)
{
    pthread_cancel(THR);
}


/******************************** end callbacks.c ***********************/





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