如何在perl中锁定成员变量?

如何在perl中锁定成员变量?,perl,Perl,我用perl编写了一个多线程脚本,然后尝试将其转换为一个对象。然而,我似乎不知道如何锁定成员变量。最接近我的是: #!/usr/bin/perl package Y; use warnings; use strict; use threads; use threads::shared; sub new { my $class = shift; my $val :shared = 0; my $self = { x => \$val }; bless $se

我用perl编写了一个多线程脚本,然后尝试将其转换为一个对象。然而,我似乎不知道如何锁定成员变量。最接近我的是:

#!/usr/bin/perl
package Y;
use warnings;
use strict;
use threads;
use threads::shared;

sub new
{
  my $class = shift;
  my $val :shared = 0;
  my $self =
  {
    x => \$val
  };
  bless $self, $class;
  is_shared($self->{x}) or die "nope";
  return $self;
}

package MAIN;
use warnings;
use strict;
use threads;
use threads::shared;
use Data::Dumper;

my $x = new Y();
{
  lock($x->{x});
}
print Dumper('0');                 # prints: $VAR = '0';
print Dumper($x->{x});             # prints: $VAR = \'0';
print "yes\n" if ($x->{x} == 0);   # prints nothing
#print "yes\n" if ($$x->{x} == 0);  # dies with msg: Not a SCALAR reference
my $tmp = $x->{x};                 # this works.  Must be a order of precedence thing.
print "yes\n" if ($$tmp == 0);     # prints: yes


#++$$x->{x};                        # dies with msg: Not a SCALAR reference
++$$tmp;
print Dumper($x->{x});             # prints: $VAR = \'1';
这允许我锁定成员var
x
,但这意味着我需要两个成员变量,因为实际的成员var实际上无法通过赋值、递增等方式进行操作。我甚至无法对其进行测试

编辑


我认为应该将这个问题重命名为“如何在perl中解除对成员变量的引用?”因为问题似乎可以归结为这个问题。使用
$$x->{x}
是无效的语法,不能使用括号强制执行优先级规则。也就是说,
$($x->{x})
不起作用。使用临时引用是可行的,但很麻烦。

我不明白您试图用线程和锁定来做什么,但是在使用引用的方式中有一些简单的错误

$x->{x}
是对标量的引用,因此表达式

$x->{x} == 0
++$$x->{x}
两人看起来都很可疑
$$x->{x}
被解析为
{$$x}->{x}
(取消引用
$x
,然后将其视为哈希引用,并使用键
x
查找值)。我想你是说

${$x->{x}} == 0
++${$x->{x}}

其中,
${$x->{x}}
意味着将
$x
视为哈希引用,在该哈希中查找键
x
的值,然后撤销该值。

示例代码中没有线程。@mob我没有添加实际线程,因为没有必要显示它不起作用。如果我尝试锁定一个成员变量,它会死掉/发出嘎嘎声。
is_shared()
函数也显示它不可共享。就是这样,我以前尝试过使用括号而不是大括号。谢谢