Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using threads on perl/tk to avoid window freeze/not responding

I am trying to use threading in my perl/tk application so that it won't freeze while connecting to a remote mysql server.

#!/usr/bin/perl
use warnings;
use strict;
use DBI;
use DBD::mysql;
use Tk;
use threads;
use threads::shared;

our $type="mysql";
our $database="b_db";
our $host="mysite.com";
our $port="3306";
our $tablename="tc";
our $user="example";
our $pwd="********";
our $dsn="dbi:$type:$database:$host:$port";

my $thr=threads->create(\&con);

our $mw=new MainWindow;
$mw->Button(-text=>"Connect",-command=>\&con)->pack;
MainLoop; 
sub con{
    our $connect=DBI->connect($dsn,$user,$pwd)or die &mysql_Err;
    print "done connecting\n" if $connect;
    print "error\n" unless $connect;
}
$thr->detach;

but it still freezes when it tries to connect. I have tried to use tk/fileevent:

#!/usr/bin/perl
use DBI;
use DBD::mysql;
use Tk;

our $type="mysql";
our $database="b_db";
our $host="mysite.com";
our $port="3306";
our $tablename="tc";
our $user="example";
our $pwd="********";
our $dsn="dbi:$type:$database:$host:$port";

our $mw=new MainWindow;
$mw->Button(-text=>"Connect",-command=>\&con)->pack;

sub con{
    our $connect=DBI->connect($dsn,$user,$pwd)or die &mysql_Err;
    $mw->fileevent($connect, "readable", \&contquery);
}

sub contquery{
    $query="SELECT * FROM products ORDER BY id";
    $queryhandle=$connect->prepare($query);
    $queryhandle->execute;
    $queryhandle->bind_columns(undef, \$product_id, \$price, \$product_name,  \product_type);
    while($queryhandle->fetch()){
        print <<print;
Product Name: $product_name | Type: $product_type | Prict: $price
print
    }
}
MainLoop;

but it still freezes. Can anyone advise me on what might be the reason for this?

like image 925
Muskovitz Avatar asked Feb 04 '26 05:02

Muskovitz


1 Answers

See PerlMonks: Tk isn't thread-safe.

  1. Create the thread before any Tk widgets are created.
  2. Don't touch any Tk objects from the thread, use shared variables for communication.
like image 104
choroba Avatar answered Feb 09 '26 01:02

choroba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!