pit*_*408 3 perl multithreading thread-safety
在Java中,当我创建线程并共享一个对象时,我有时会想让线程访问相同的对象方法,但我不知道它们是在同一时间做什么的.因此,为了避免这种情况,我将对象方法定义为Synchronized方法,如下所示.
同步实例方法:
class class_name {synchronized type method_name(){\ statement block}}
方法中的所有语句都成为synchronized块,而实例对象是锁.这意味着如果我告诉一个线程使用这个方法,它将等到前一个线程完成使用该方法.有没有办法在Perl中执行此操作?
在构造函数中创建一个互斥锁.
sub new {
...
my $mutex :shared;
$self->{mutex_ref} = \$mutex;
...
}
Run Code Online (Sandbox Code Playgroud)
输入方法时锁定它.
sub method {
my ($self) = @_;
lock ${ $self->{mutex_ref} };
...
}
Run Code Online (Sandbox Code Playgroud)
演示:
use strict;
use warnings;
use threads;
use threads::shared;
use feature qw( say );
sub new {
my ($class, $id) = @_;
my $mutex :shared;
return bless({
mutex_ref => \$mutex,
id => $id,
}, $class);
}
sub method {
my ($self) = @_;
lock ${ $self->{mutex_ref} };
say sprintf "%08X %s %s", threads->tid, $self->{id}, "start";
sleep(2);
say sprintf "%08X %s %s", threads->tid, $self->{id}, "end";
}
my $o1 = __PACKAGE__->new('o1');
my $o2 = __PACKAGE__->new('o2');
for (1..3) {
async { my ($o) = @_; $o->method() } $o1;
async { my ($o) = @_; $o->method() } $o2;
}
$_->join for threads->list();
Run Code Online (Sandbox Code Playgroud)
$o1->method同时运行.$o1->method并$o2->method可以同时运行.实际上,如果你打算共享对象 - 这是通过将对象作为参数传递给async上面代码的int 来完成的 - 你可以使用对象本身作为锁.
use threads::shared qw( shared_clone );
sub new {
my ($class, ...) = @_;
return shared_clone(bless({
...
}, $class));
}
Run Code Online (Sandbox Code Playgroud)
输入方法时锁定它.
sub method {
my ($self) = @_;
lock %$self;
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3701 次 |
| 最近记录: |