-
Notifications
You must be signed in to change notification settings - Fork 0
/
threadspool.pm
55 lines (49 loc) · 1.14 KB
/
threadspool.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package perluim::threadspool;
use strict;
use warnings;
use threads;
use Thread::Queue;
use Data::Dumper;
sub new {
my ($class,$cbRef,$threadsNumber,$maxRow) = @_;
my $this = {
cb => $cbRef,
queue => Thread::Queue->new,
count => $maxRow,
threads => undef,
done => 0
};
my $blessed = bless($this,ref($class) || $class);
my @Threads = ();
while($threadsNumber--) {
my $thr = threads->new(sub {
my $Element;
while (not $blessed->{count} <= $blessed->{done} and $Element = $blessed->{queue}->dequeue) {
my $res = $blessed->{cb}($Element);
if($res eq "done") {
$blessed->{done}++;
}
}
});
push(@Threads,$thr);
}
$blessed->{threads} = \@Threads;
return $blessed;
}
sub enqueue {
my ($self,@elements) = @_;
$self->{queue}->enqueue(@elements);
}
sub await {
my ($self) = @_;
foreach my $thr (@{$self->{threads}}) {
$thr->join;
}
}
sub stop {
my ($self) = @_;
foreach my $thr (@{$self->{threads}}) {
$thr->detach;
}
}
1;