- 论坛徽章:
- 1
|
#------------------------------------------------------
最近上面長官要我用multithread的方式將我寫的一個很耗時的程序
加快執行效率,但是我用perl 5.8 的ithread後,發現他在thread間
無法傳送handle
Error如下:
thread failed to start: DBD::Informix::db prepare failed: handle 2
is owned by thread 2003af28 not current thread 20557548
(handles can't be shared between threads and your driver
may need a CLONE method added) at thread.pl line 58.
我原本的想法是利用Thread:ueue由main thread將資料放入輸入
的queue中,然後由前三個thread將queue中的資料取出,並執行
一些測試動作後,放入輸出的queue中。最後由第四個threads將輸出的
queue中的數據,回寫入資料庫中...但是如上面錯誤所見..他建議我要用
CLONE method..不知道有沒有人知道怎麼樣clone?
我很少寫clone方面的東西...有點搞不清楚怎樣 clone..
#!/usr/bin/perl
use threads qw(yield);
use threads::shared;
use Thread:ueue;
my $stream_1 = new Thread:ueue;
my $stream_2 = new Thread:ueue;
my $qdatabase = "XXXXX\@"; # 數據庫的名稱
my $dbh=&DB_CON($qdatabase);
print "ya!!";
#$stream_3 = new Thread:ueue;
$thr1 = threads->;new(\&sub2,1,$stream_1,$stream_2);
print "oh!!";
$thr2 = threads->;new(\&sub2,2,$stream_1,$stream_2);
$thr3 = threads->;new(\&sub2,3,$stream_1,$stream_2);
$thr4 = threads->;new(\&sub3,4,$stream_2,$dbh);
my $sql="select * from test";
my $sth_s = $dbh->;prepare(qq{ $sql })|| die "can't preapre $!";
$sth_s->;execute || die "can't execute $!";
my $count = 0;
while(my @aa=$sth_s->;fetchrow_array()){
print "XXXX$count : @aa\n";
$cmd = join("##",@aa);
$stream_1->;enqueue($cmd);
$count++;
# last if (++$count==10);
}
$stream_1->;enqueue(undef);
$stream_1->;enqueue(undef);
$stream_1->;enqueue(undef);
$stream_2->;enqueue(undef);
$thr1->;join;
$thr2->;join;
$thr3->;join;
$thr4->;join;
#------------------------------------------------------
sub sub3{
my ($num,$ostream,$dbh ) = @_;
if(defined $dbh){
my $sql="select * from test";
my $sth=$dbh->;prepare(qq { $sql } ) || die "can't prepare: $!";
$sth->;execute || die "can't execute: $!";
while(my @aa=$sth->;fetchrow_array){
print "$num : @aa\n";
}
}
}
sub sub2{
my ($num,$istream,$ostream) = @_;
#print "Success!!\n";
while(my $data=$istream->;dequeue){
print "$num : $data \n";
$ostream->;enqueue($data);
}
}
sub DB_CON
{
my ($qdatabase) = @_;
use DBI;
$ENV{"INFORMIXDIR"}="/usr/informix";
$ENV{"INFORMIXSERVER"}="abcd";
if ($qdatabase =~m"L123"
{
$ENV{"DB_LOCALE"}="en_US.8859-1";
$ENV{"CLIENT_LOCALE"}="en_US.8859-1";
}
else
{
$ENV{"DB_LOCALE"}="zh_TW.big5";
$ENV{"CLIENT_LOCALE"}="zh_TW.big5";
}
my $dbh = DBI->;install_driver('Informix');
my $user="abc";
my $pwd="cdef";
my $dbh = DBI->;connect("dbi:Informixqdatabase",$user,$pwd)
|| die ("Can't connect to $qdatabase"
return $dbh;
} |
|