Reputation: 101
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?
Upvotes: 3
Views: 360
Reputation: 241828
See PerlMonks: Tk isn't thread-safe.
Upvotes: 4
Reputation: 53478
You're misunderstanding threading and sharing. our
doesn't share across threads. You need to declare a variable as shared
in order to do that.
Otherwise from the moment you create
the subthread, they have their own local copy of all the variables. This will almost certainly be your problem - your thread connects to the database then exits, completely independent of the main thread.
our
also doesn't do what you think it does - that's for sharing package variables (e.g. nothing at all to do with threading), which is irrelevant in your code. Stick with my
.
You might be able to do:
my $db_handle : shared;
And then in the thread:
$db_handle = DBI->connect($dsn, $user, $password);
But bear in mind you cannot be sure when that'll complete, so it's very important you check before you try and use it in another thread.
Upvotes: 2