我可以像使用互斥锁一样使用threads :: shared模块中的锁吗?

时间:2014-05-13 12:19:17

标签: multithreading perl shared anyevent

我正在使用AnyEvent每X分钟触发一次事件。某些过程很长,记录在数据库中的结果有时很长(有时超过3秒)。我想确保只有一个函数可以同时访问我的数据库。所以我使用threads :: shared模块中的lock。这是我的代码:

main.pl:

my $var :shared;
$var = 0;

my $w1 = AnyEvent->timer(after => 0, interval => 120, cb => sub {
my @targeted_users = TargetUsers::get_targeted_account_from_followers($dbh,$account,'myrhline');
TargetUsers::save_users_to_follow($dbh,'RH',$var,@targeted_users);
});

my $w2 = AnyEvent->timer(after => 0, interval => 120, cb => sub {
my @targeted_users2 = TargetUsers::get_targeted_account_from_followers($dbh,$account2,'actuel_rh');
TargetUsers::save_users_to_follow($dbh,'RH',$var,@targeted_users2);
});

AnyEvent::Loop::run;

TargetUsers:

sub save_users_to_follow{
my ($dbh,$topic,$var,@targeted_users) = @_;

lock($var); #I call lock($var) to lock the access to the database.

my @array1 = ();

$dbh->{AutoCommit} = 0;

my $sth2 = $dbh->prepare(
"UPDATE People_TO_FOLLOW
         SET   Pertinence       = Pertinence + 1
         WHERE Id_user = ?");

my $tuples_update = $sth2->execute_array(
{ ArrayTupleStatus => \my @tuple_status_update },
\@targeted_users,
);

if ($tuples_update) {
print "Successfully updated $tuples_update records\n";
}
else {
for my $tuple_1 (0..$#targeted_users) {
    my $status_1 = $tuple_status_update[$tuple_1];
    $status_1 = [0, "Skipped"] unless defined $status_1;
    next unless ref $status_1;
    printf "Failed to update (%s): %s\n",
        $targeted_users[$tuple_1], $status_1->[1];
}
}
$sth2->finish();

my $sth = $dbh ->prepare(
"INSERT OR IGNORE INTO People_TO_FOLLOW(Id_user,Topic,Already_followed,Pertinence) VALUES (?,'$topic',0,1)");

my $tuples_insert = $sth->execute_array(
{ ArrayTupleStatus => \my @tuple_status_insert },
\@targeted_users,
);

if ($tuples_insert) {
print "Successfully inserted $tuples_insert records\n";
}
else {
for my $tuple_2 (0..$#targeted_users) {
    my $status_2 = $tuple_status_insert[$tuple_2];
    $status_2 = [0, "Skipped"] unless defined $status_2;
    next unless ref $status_2;
    printf "Failed to insert (%s): %s\n",
    $targeted_users[$tuple_2], $status_2->[1];
}
}
$sth->finish();
$dbh->commit;
$dbh->{AutoCommit} = 1;    
}

但我收到此错误:“锁定只能用于共享值”

请问您有什么想法吗?感谢

1 个答案:

答案 0 :(得分:4)

您有两个名为$var的变量,main.pl中的变量和save_users_to_follow中的变量。前者是共享变量,但是你试图锁定后者。

将var从main移动到TargetUsers,或将对lock var的引用传递给save_users_to_follow