다릅니다.
sub new {
...
my $mutex :shared;
$self->{mutex_ref} = \$mutex;
...
}
입력 할 때 잠급니다.
sub method {
my ($self) = @_;
lock ${ $self->{mutex_ref} };
...
}
데모 : 동시에 $o1->method
실행에
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();
이
- 아니 두 통화.
$o1->method
과 $o2->method
은 동시에 실행할 수 있습니다. 당신이 — 어쨌든 객체를 공유 할 거라면
사실이 그가 코드 — 위에 당신이 잠금으로 객체 자체를 사용할 수 async
INT에 인수로 객체를 전달하여 이루어졌다.
use threads::shared qw(shared_clone);
sub new {
my ($class, ...) = @_;
return shared_clone(bless({
...
}, $class));
}
입력 할 때 잠급니다. (5.005)에서
sub method {
my ($self) = @_;
lock %$self;
...
}
이미 매우 간단했지만, 심지어 더 간단합니다. – ikegami
실제로 위의 코드에서 threads :: shared :: shared_clone을 지정해야합니다. 그렇지 않으면 shared_clone이 패키지에 없으므로 오류가 발생합니다. 귀하의 예제는 클래스를 정의하기 위해 패키지를 지정하는 것을 게을리하여 코드가 실제로 객체 지향적이 아니기 때문에 작동합니다. – CDahn
@CDahn, 아니요,'use threads :: shared qw (shared_clone); '을 사용하여 가져올 수 없습니다. 나는 이것을 추가했다. /// 당신은 착각을합니다; 나는 클래스를 정의했고 그 클래스의 객체를 만들었습니다. – ikegami