Re: Updating GUI from a callback using threads



On Tue, 5 Aug 2008 13:54:45 +0200
"Tadej BorovÅak" <tadeboro gmail com> wrote:

Hello,

I need to develop quite simple GUI for a project at the University.

The main task of this GUI is to present results of a search to an
user. And since those searches (which are executed inside callbacks)
can take a few minutes to finish, I would like to update my GUI during
the search as an indication to a user, that program is working (and
not just standing there).

Below is a sample program that shows what I'm trying to achieve (when
the program exits, it prints error message "GLib-GObject-CRITICAL **:
g_object_unref: assertion `G_IS_OBJECT (object)' failed at test.pl
line 37." for each widget).

Here is a quick (imperfect, no clean exit), but running fix to your program.


#!/usr/bin/perl
# test.pl - playing with threads
use strict;
use warnings;
use utf8;
use threads;
use threads::shared;
use Time::HiRes qw{ sleep };
use Glib qw{ TRUE FALSE };
use Gtk2 qw{ -init -threads-init };

Glib::Object->set_threadsafe (TRUE);

#setup shared hash
my %shash;
share(%shash); #will work for first level keys
$shash{'go'} = 0;

Glib::Object->set_threadsafe (TRUE);

# my global variables
my $window;
my $vbox;
my $progress;
my $button;

$window = Gtk2::Window->new( 'toplevel' );
$window->set_title( "Threaded program" );
$window->signal_connect( 'delete-event', sub { Gtk2->main_quit(); } );

$vbox = Gtk2::VBox->new( FALSE, 5 );
$window->add( $vbox );

$progress = Gtk2::ProgressBar->new();
$progress->set_pulse_step( 0.05 );
$vbox->pack_start( $progress, FALSE, TRUE, 0 );

$button = Gtk2::Button->new_with_label( "Test" );

$button->signal_connect( 'clicked', \&cb_butt, $progress );

$vbox->pack_start( $button, FALSE, TRUE, 0 );
$window->show_all();

my $thr = threads->create( sub { 
        
        while(1){
           if($shash{'go'}){
               print "thread going\n";
               sleep( 5 ); 
               $shash{'go'} = 0;
            }else{
            print "snore\n";
            sleep 1}
        }
        
    });

Gtk2->main();

exit( 0 );


sub cb_butt {
my $button = shift;

    my $progress = shift;
    
    $shash{'go'} = 1;

    my $c = 0;

    while( $shash{'go'} ) {

        local $| = 1;
         
       Glib::Idle->add(
                   sub{
                    $progress->pulse;
                    return FALSE;
                   });

    while( Gtk2->events_pending() ){Gtk2->main_iteration() }

    print( "debug: " . ++$c . "\n" );
    sleep( 0.1 );

    }

#    $thr->join();
}
__END__

zentara

-- 
I'm not really a human, but I play one on earth.
http://zentara.net/Remember_How_Lucky_You_Are.html 



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