gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 13:17:29 25 4
gpt4 key购买 nike

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

主要.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;

目标用户:
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;
}

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

你有什么想法吗?谢谢

最佳答案

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

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

关于multithreading - 我可以像互斥锁一样使用threads::shared模块中的锁吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23631082/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com