NAME
Ekorn::Pipeline::Workers::Manual::HowTo - Ekorn::Pipeline::Workers user guide
DESCRIPTION
Ekorn::Pipeline::Workers gives you three stages: in_workers, in_workers_as_ready and once_per. Each one lets a pipeline hand its values to several workers, which do the work side by side, instead of one value after another.
A worker is a separate perl, started for you. You write the work for one value as a function, in a module of your own. Each worker loads that module, and runs the function for each value it's sent. The stage passes the results on to the rest of the pipeline, like any other stage.
The rest of your program doesn't change. It still runs one line after another. Only the workers work side by side.
This guide is a set of recipes. Each one solves a single problem, and each one is complete: a program, and the module it uses. Save them where the recipe says, run the program, and it prints what the guide says it prints. Every recipe is tested that way, on Linux, macOS and Windows.
Is this the guide you need?
Ekorn::Pipeline has two distributions for doing many things at once. Which one fits depends on what each value's work waits for:
Waiting on the network, with a library that can wait without stopping the program, such as Mojo::UserAgent or IO::Async: use Ekorn::Pipeline::Futures, and its own guide, Ekorn::Pipeline::Futures::Manual::HowTo. One process waits on many requests at once, and your code needn't be in a module.
Waiting on something that stops the program while it waits, such as a database query through the DBI, or a module with only an ordinary, blocking interface; or keeping the CPU busy, such as compressing files or crunching numbers: use this one. Each value's work runs in a worker of its own.
Neither, because each value's work takes microseconds: use an ordinary stage. Starting workers takes milliseconds, so they only pay for work that takes longer.
Where to start
The guide is long, but you needn't read it all. Pick the path that fits you:
New to workers? Read Before you start, then chapters 1 and 2.
Used Parallel::ForkManager, MCE or threads? Read A worker is a new perl, not a copy of yours, then chapter 2: each of these workers is a new perl, not a copy, and that changes how you set them up.
Using DBIx::Squirrel, or the DBI? Read chapter 2, then chapters 3 and 4.
Keeping the CPU busy? Read chapter 1, then chapters 7 and 8.
Already using Ekorn pipelines? Read chapter 1, then chapters 5 and 9, where Ekorn's own parts meet the stages.
Choosing between Workers, Futures or neither? Read One problem, three ways, then chapter 7.
Something went wrong? Read chapter 6, then Every message the stages give.
Contents
Before you start: workers, modules and copies
These three short recipes show the ideas the rest of the guide is built on.
Used workers before, with Parallel::ForkManager or MCE? These workers aren't like those. Read the second recipe, A worker is a new perl, not a copy of yours, then skip to chapter 1.
Every recipe in this guide is a program and a module. To run one:
Make a folder for it, with a folder
libinside.Save the module in
lib, where the recipe says.Save the program in the recipe's folder, beside
lib, and run it.
A worker is another process
The problem
You'd like to see that the work really happens somewhere else, and not in your program.
You'll need
Ekorn::Pipeline::Workers:
cpanm Ekorn::Pipeline::Workers
The program
Save this module as lib/My/Where.pm:
package My::Where;
use v5.36;
use Time::HiRes qw(sleep);
# Give back the number of the process the work was done in. Perl keeps
# it in $$. The nap, a fifth of a second, which Time::HiRes's sleep
# allows, gives the other workers time to take a value too.
sub process_of ($value) {
sleep 0.2;
return $$;
}
1;
Then save this program as where.pl, beside lib, and run it with perl where.pl:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
my $pipeline = Ekorn::Pipeline->new(
in_workers(3, 'My::Where::process_of'),
);
my @processes = $pipeline->(qw(Abba Blur Cream));
my %different = map { $_ => 1 } @processes;
say scalar(@processes), ' values, done in ', scalar(keys %different), ' processes';
# 3 values, done in 3 processes
say 'none of them the program: ', ($different{$$} ? 'no' : 'yes');
# none of them the program: yes
How it works
Every running program is a process, with a number of its own, which Perl keeps in $$. process_of gives back the number of the process it ran in.
in_workers(3, ...) starts three workers, each a process of its own, and sends each one a name. So the three names come back with three different numbers, and none of them is the program's own.
A process has its own memory. Nothing one process does to its variables changes another's. That's what lets workers run side by side safely, and it's why the next recipes look the way they do.
What can go wrong
Nothing here, but the work happening elsewhere is what every later mistake comes from: the worker can't see your program's variables, and what it's given is a copy.
Where next
A worker is a new perl, not a copy of yours.
A worker is a new perl, not a copy of yours
The problem
Your function needs a setting. You'd like to set it in your program, and have the workers use it.
You'll need
Ekorn::Pipeline::Workers, as before.
The program
Save this module as lib/My/Greeting.pm:
package My::Greeting;
use v5.36;
# A setting, with the value it has when the module is loaded.
our $WORD = 'hello';
sub greet ($name) {
return "$WORD, $name";
}
1;
Then save this program as greet.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
use My::Greeting;
# Change the setting, in this program.
$My::Greeting::WORD = 'goodbye';
say My::Greeting::greet('Abba'); # goodbye, Abba
my $pipeline = Ekorn::Pipeline->new(
in_workers(2, 'My::Greeting::greet'),
);
say for $pipeline->(qw(Abba Blur));
# hello, Abba
# hello, Blur
How it works
Called in the program, greet sees the setting the program changed: "goodbye". In the workers, it says "hello".
That's because each worker is a new perl, started from nothing. It loads My::Greeting for itself, so $WORD is what the module sets as it loads. What your program did after loading it happened in your program's memory, which no worker can see.
Tools such as Parallel::ForkManager and MCE make each worker a copy of your program, taken as it runs, with all its variables. These workers aren't copies, on any system. Copies don't work on Windows, where a copy of a program tears down what the program holds as it leaves, such as a database connection. A new perl inherits nothing, so it can't harm what your program holds, and it behaves the same on Windows, Linux and macOS.
So the rules for these stages all come from one fact: a worker knows only what it loads and what it's sent.
The work is a function in a module, which a worker can load, never a block of code inside your program.
A setting a function needs is sent to it, as chapter 2 shows, not set in the program.
Anything the work needs open, such as a database connection, is opened by the worker itself, as chapter 2 shows too.
What can go wrong
Handing the stage a block of code, as you would to map, is the mistake to expect. A worker can't reach code inside your program, so the stage refuses it as it's made:
use v5.36;
use Ekorn::Pipeline::Workers qw(in_workers);
# A mistake: a block of code, which no worker can reach.
eval { in_workers(2, sub ($name) { "hello, $name" }) };
print $@; # Expected the function to be a named sub in a module, not an anonymous one: a worker is a new perl, which it can't reach at ...
The fix is to move the code into a function in a module, as My::Greeting does, and name it.
Where next
What a worker is given is a copy.
What a worker is given is a copy
The problem
Your function changes the value it's given. You'd like to know whether your program sees the change.
You'll need
Ekorn::Pipeline::Workers, as before.
The program
Save this module as lib/My/Album.pm:
package My::Album;
use v5.36;
# Add the decade to an album, and give the album back.
sub add_decade ($album) {
$album->{decade} = 10 * int($album->{year} / 10) . 's';
return $album;
}
1;
Then save this program as copy.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
my $album = {title => 'Parklife', year => 1994};
my $pipeline = Ekorn::Pipeline->new(
in_workers(2, 'My::Album::add_decade'),
);
my($result) = $pipeline->($album);
say "the result: $result->{title}, $result->{decade}"; # the result: Parklife, 1990s
say 'the album: ', join ', ', sort keys %$album; # the album: title, year
How it works
To send the album to a worker, the stage turns it into bytes, with Storable, which comes with Perl, and the worker turns the bytes back into a hash of its own. That's a copy. The worker adds decade to its copy, and sends that back the same way, as a copy again.
So the result has the decade, and your program's own $album is just as it was. Use what the stage gives back, never what you sent.
What can go wrong
Only what Storable can turn into bytes can go: numbers, strings, and arrays, hashes and objects made of them. A code reference, an open file or a database handle can't. Sending one fails, and says which value it was:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
# A mistake: an album holding a code reference, which can't be copied.
my $album = {title => 'Parklife', year => 1994, rate => sub {5}};
my $pipeline = Ekorn::Pipeline->new(
in_workers(2, 'My::Album::add_decade'),
);
eval { $pipeline->($album) };
print $@;
# Pipeline stage #1 failed at ...
# in_workers can't send value #1 to a worker: Can't store CODE items at ...
The fix is to send plain data: the album's title and year. Whatever the worker needs beyond that, it loads or opens itself.
Where next
Chapter 1 puts workers to work.
1. First steps
These recipes show what the stages do, with sleep standing in for slow work, so that every one runs anywhere, with nothing to set up. A function that sleeps for a second behaves like a query that takes a second.
Run three slow jobs at once
The problem
You have a list of names. Looking each one up takes a second, and the library that does it makes your program wait. One after another, three names take three seconds. You'd like them to take one.
You'll need
Ekorn::Pipeline::Workers. Install it from CPAN:
cpanm Ekorn::Pipeline::Workers
The program
Make a folder for the recipe. In it, make a folder lib, and in that a folder My. Save this module as lib/My/Slow.pm:
package My::Slow;
use v5.36;
# This stands in for a slow look-up, such as a database query.
# It waits for one second, then gives its answer, after the number of
# the process it ran in, which Perl keeps in $$.
sub look_up ($name) {
sleep 1;
return "$$ found $name";
}
1;
Then save this program as look-up.pl, in the recipe's folder, beside lib, and run it with perl look-up.pl:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Time::HiRes qw(time);
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
my $pipeline = Ekorn::Pipeline->new(
in_workers(3, 'My::Slow::look_up'),
);
say "$$ is the program"; # ... is the program
my $started = time;
say for $pipeline->(qw(Abba Blur Cream));
# ... found Abba
# ... found Blur
# ... found Cream
printf "took %d s\n", time - $started; # took 1 s
How it works
My::Slow is an ordinary module, with one function, look_up, the work for one name. It's in a module, not in the program, because each worker is a new perl: it can load a module, but it can't see anything inside your program.
use FindBin and use lib "$FindBin::Bin/lib" tell perl to look for modules in the lib folder beside the program, wherever you run it from. The workers look in the same places as the program, so they find My::Slow too.
use Ekorn::Pipeline::Workers qw(in_workers) imports the stage. All three stages are imported by default, so qw(in_workers) isn't needed, but this guide names what each program uses, so you can see where every name comes from.
in_workers(3, 'My::Slow::look_up') is the stage. The 3 says how many workers to start. 'My::Slow::look_up' names the function, with its module, as a string. The program loads My::Slow as the stage is made, to check the function is there.
When the first name reaches the stage, it starts three workers. It sends each a name, and each runs look_up on its own, at the same time as the others. So the three seconds of sleeping happen together, and the run takes about one second, not three.
Each line starts with the number of the process that did the work: three different numbers, none of them the program's. Yours will differ from run to run, as a new process gets a new number.
The results come out in the order the names went in, whichever worker finished first. When the run is over, the workers leave.
Here sleep is fine. In a worker, waiting holds up only that worker, never the others or the program.
What can go wrong
Leave out the use lib line, and perl can't find My::Slow. The stage says so as it's made, with perl's own reason:
use v5.36;
use Ekorn::Pipeline::Workers qw(in_workers);
# A mistake: no use lib, so perl doesn't look in lib for My::Slow.
eval { in_workers(3, 'My::Slow::look_up') };
print $@; # Expected the function's module, My::Slow, to load: Can't locate My/Slow.pm in @INC ...
The fix is the two lines at the top of the program, use FindBin and use lib "$FindBin::Bin/lib". If your module is installed, as one from CPAN is, you don't need them.
Where next
See the time it saves measures the difference.
See the time it saves
The problem
You'd like to see what the workers save, and what they cost, before you use them.
You'll need
Ekorn::Pipeline::Workers, as before.
The program
Save this module as lib/My/Slow.pm:
package My::Slow;
use v5.36;
# A look-up that takes one second, giving the number of its process.
sub look_up ($name) {
sleep 1;
return "$$ found $name";
}
1;
Then save this program as timed.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Time::HiRes qw(time);
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
my @names = qw(Abba Blur Cream Doves);
for my $workers (1, 4) {
my $pipeline = Ekorn::Pipeline->new(
in_workers($workers, 'My::Slow::look_up'),
);
my $started = time;
my @found = $pipeline->(@names);
printf "%d workers took %d s\n", $workers, time - $started;
}
# 1 workers took 4 s
# 4 workers took 1 s
How it works
With one worker, the four look-ups run one after another, as they would without workers: four seconds. With four, they run side by side, and the four seconds of waiting take one.
Each run starts its own workers, as its first value arrives, and ends them as it finishes. Starting a worker means starting a perl, which takes about 13 milliseconds on macOS, and longer on Windows, where four take a quarter to half a second. So the second run's one second is a little more than one, which rounding down, as %d does, hides.
That's the trade the stages make. They pay off when each value's work takes far longer than starting a perl, as a second does. They don't pay off when it takes microseconds: then the workers' start is all you'd measure, and an ordinary stage is faster. What starting workers costs has the numbers.
What can go wrong
A run of one value gains nothing from many workers: one value keeps one worker busy, and the rest start for nothing. The stages are for many values.
Where next
Choose how many workers
The problem
You have more values than you'd like workers. You'd like to know what happens to the rest, and how many workers to ask for.
You'll need
Ekorn::Pipeline::Workers, as before.
The program
Save this module as lib/My/Slow.pm:
package My::Slow;
use v5.36;
# A look-up that takes one second, giving the number of its process.
sub look_up ($name) {
sleep 1;
return "$$ found $name";
}
1;
Then save this program as how-many.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Time::HiRes qw(time);
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
my $pipeline = Ekorn::Pipeline->new(
in_workers(2, 'My::Slow::look_up'),
);
my $started = time;
my @found = $pipeline->(qw(Abba Blur Cream Doves));
printf "%d found in %d s\n", scalar @found, time - $started; # 4 found in 2 s
How it works
in_workers(2, ...) starts two workers, and no more. The first two names go to them at once. Each of the others waits for a worker to be free, and goes to the first one that is. So four one-second look-ups, two at a time, take two seconds.
How many to ask for depends on what the work waits for:
Waiting on something else, such as a database server or a slow disk: more workers than your computer has cores is fine, as most of them are waiting. Ask for as many as what they wait on can bear: a database takes only so many connections at once.
Keeping the CPU busy, such as compressing files: about as many as your computer has cores. More can't run at once, so they only add their starting.
Each worker is a whole perl, with its own memory, a few megabytes or more, with what its module loads. Dozens are fine. Thousands aren't.
What can go wrong
The number must be a whole number, 1 or more. Anything else stops the program as the stage is made:
use v5.36;
use Ekorn::Pipeline::Workers qw(in_workers);
eval { in_workers(0, 'My::Slow::look_up') };
print $@; # Expected a number of workers of 1 or more at ...
Where next
Get the results in the order the values came.
Get the results in the order the values came
The problem
Some values take longer than others. You'd like the results in the order the values came, whichever finishes first.
You'll need
Ekorn::Pipeline::Workers, as before.
The program
Save this module as lib/My/Uneven.pm:
package My::Uneven;
use v5.36;
use Time::HiRes qw(sleep);
# Abba takes longest, Blur the least.
my %seconds = (Abba => 2, Blur => 0.2, Cream => 1);
sub look_up ($name) {
sleep $seconds{$name};
return "$$ found $name";
}
1;
Then save this program as in-order.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
my $pipeline = Ekorn::Pipeline->new(
in_workers(3, 'My::Uneven::look_up'),
);
say for $pipeline->(qw(Abba Blur Cream));
# ... found Abba
# ... found Blur
# ... found Cream
How it works
use Time::HiRes qw(sleep) gives a sleep that takes fractions of a second. Perl's own takes whole seconds, so it would make sleep 0.2 no wait at all.
Blur's worker finishes first, then Cream's, then Abba's. in_workers holds Blur's and Cream's results back until Abba's is in, and passes all three on in the order the names came. That's what you want when the order means something, such as the lines of a report.
The stage holds back only so much. By default, it sends at most twice as many values as it has workers before it waits for the oldest to finish, so one slow value can't make it hold everything else.
What can go wrong
Holding back means one slow value holds up everything after it, even the results that are ready. If the order doesn't matter, take each as it's ready, as the next recipe does.
Where next
Get each result as soon as it's ready.
Get each result as soon as it's ready
The problem
The order doesn't matter to you. You'd like each result as soon as it's ready, so a slow value doesn't hold up the rest.
You'll need
Ekorn::Pipeline::Workers, as before.
The program
Save this module as lib/My/Uneven.pm:
package My::Uneven;
use v5.36;
use Time::HiRes qw(sleep);
# Abba takes longest, Blur the least.
my %seconds = (Abba => 2, Blur => 0.2, Cream => 1);
sub look_up ($name) {
sleep $seconds{$name};
return "$$ found $name";
}
1;
Then save this program as as-ready.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers_as_ready);
my $pipeline = Ekorn::Pipeline->new(
in_workers_as_ready(3, 'My::Uneven::look_up'),
);
say for $pipeline->(qw(Abba Blur Cream));
# ... found Blur
# ... found Cream
# ... found Abba
How it works
in_workers_as_ready is in_workers, except that it passes each result on as soon as its worker sends it back. Blur's is first, after a fifth of a second, then Cream's, then Abba's.
It doesn't stop at the first result: every value's results are passed on, each as it's ready. Only the order changes.
What can go wrong
The order now depends on timing, so it can change from one run to the next. When you need to know which value a result came from, put it in the result, as look_up does with the name, or ask Ekorn, as Know which value each result came from shows.
Where next
Give several results, or none.
Give several results, or none
The problem
For some values there's nothing to give, and for others there are several things. You'd like the function to say so.
You'll need
Ekorn::Pipeline::Workers, as before.
The program
Save this module as lib/My/Tracks.pm:
package My::Tracks;
use v5.36;
my %tracks = (
Abba => ['Waterloo', 'Dancing Queen'],
Blur => ['Parklife'],
);
# Give each of an artist's tracks, or nothing for one we don't know.
sub tracks_of ($artist) {
return @{ $tracks{$artist} // [] };
}
1;
Then save this program as tracks.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
my $pipeline = Ekorn::Pipeline->new(
in_workers(2, 'My::Tracks::tracks_of'),
);
say for $pipeline->(qw(Abba Cream Blur));
# Waterloo
# Dancing Queen
# Parklife
How it works
The function runs in a worker, but it returns as any Ekorn stage does: nothing, to drop the value; one result, to pass it on; or several, each passed on in its turn. Cream has no tracks, so it gives nothing, and Abba gives two.
The results stay in the order the values came, as before: both of Abba's, then Blur's.
What can go wrong
What the function returns crosses back as a copy, as the value did, so the same limits hold: return plain data, never an open file or a code reference. To see what happens if you do, save this as lib/My/Tracks.pm, in place of the module above:
package My::Tracks;
use v5.36;
# A mistake: a filehandle, here the worker's own input, which can't
# cross back.
sub handle_of ($artist) {
return \*STDIN;
}
1;
Then run this. The result can't cross, and the message names the value:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
my $pipeline = Ekorn::Pipeline->new(
in_workers(2, 'My::Tracks::handle_of'),
);
eval { $pipeline->('Abba') };
print $@;
# Pipeline stage #1 failed at ...
# in_workers can't send back the results of value #1: Can't store GLOB items
The fix is to give back what a file holds, such as its lines, rather than the file.
Where next
Name the function with a code reference.
Name the function with a code reference
The problem
You'd rather name the function as you would for any other code, as \&My::Slow::look_up, than as a string.
You'll need
Ekorn::Pipeline::Workers, as before.
The program
Save this module as lib/My/Slow.pm:
package My::Slow;
use v5.36;
# A look-up that takes one second, giving the number of its process.
sub look_up ($name) {
sleep 1;
return "$$ found $name";
}
1;
Then save this program as reference.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
use My::Slow ();
my $pipeline = Ekorn::Pipeline->new(
in_workers(3, \&My::Slow::look_up),
);
say "$$ is the program"; # ... is the program
say for $pipeline->(qw(Abba Blur Cream));
# ... found Abba
# ... found Blur
# ... found Cream
How it works
\&My::Slow::look_up is a reference to the function. The stage asks Perl for its name, My::Slow::look_up, and sends the workers the name, as before: a worker can't be sent the code itself. So the two ways of naming the function do the same, and the process numbers show the work still ran in the workers, not in the program, though the program has the function loaded too.
A reference catches a misspelt name when the program is compiled, under use strict, which use v5.36 turns on, if the module is loaded: hence use My::Slow ().
What can go wrong
The reference must be to a function in a module. One to a function in your program won't do, as no worker loads your program:
use v5.36;
use Ekorn::Pipeline::Workers qw(in_workers);
# A mistake: a function in the program, which no worker loads.
sub look_up ($name) { return "found $name" }
eval { in_workers(3, \&look_up) };
print $@; # Expected the function to be a sub in a module, not the program's main::look_up: a worker is a new perl, which loads modules, not the program at ...
The fix is to move it into a module, as My::Slow.
Where next
Chapter 2 sets each worker up before its first value.
2. Setting each worker up
Some work needs something ready before the first value: a table loaded, a connection opened, a setting read. Doing that for every value wastes time, and doing it in your program doesn't reach the workers. These recipes do it once in each worker, as it starts, and tidy up as it leaves.
Set each worker up once, with init
The problem
Before it can look anything up, your function needs a table, which takes a second to load. Loading it for every name would take a second a name. You'd like each worker to load it once.
You'll need
Ekorn::Pipeline::Workers:
cpanm Ekorn::Pipeline::Workers
The program
Save this module as lib/My/Years.pm:
package My::Years;
use v5.36;
# Load the table: run once in each worker, as it starts. The sleep
# stands in for reading a large file, say. What it returns is given
# to look_up, after each name.
sub load_table () {
sleep 1;
return {Abba => 1972, Blur => 1988, Cream => 1966, Doves => 1998};
}
# Look a name up in the table this worker loaded.
sub look_up ($name, $table) {
return "$$ found $name, formed $table->{$name}";
}
1;
Then save this program as init.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Time::HiRes qw(time);
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
my $pipeline = Ekorn::Pipeline->new(
in_workers(2, 'My::Years::look_up',
init => 'My::Years::load_table',
),
);
my $started = time;
say for $pipeline->(qw(Abba Blur Cream Doves));
# ... found Abba, formed 1972
# ... found Blur, formed 1988
# ... found Cream, formed 1966
# ... found Doves, formed 1998
printf "took %d s\n", time - $started; # took 1 s
How it works
init => 'My::Years::load_table' names a function each worker runs once, as it starts, before it's sent a value. It's named as the main function is: with its module, as a string, or as a code reference to a function in a module.
Whatever init returns is passed to the main function after each value. So each worker calls look_up('Abba', $table), with the table it loaded itself.
Both workers load their tables at the same time, as they start, so the run pays one second for loading, not one a name. The stage waits until every worker's init is done before it sends the first name.
What can go wrong
If init dies, there's nothing to run the work with, so the whole run fails before any value is sent, with init's message. To see it, save this as lib/My/Years.pm, in place of the module above:
package My::Years;
use v5.36;
# A mistake: an init that fails.
sub no_table () {
die "no table today\n";
}
sub look_up ($name, $table) {
return "$$ found $name, formed $table->{$name}";
}
1;
Then run this:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
my $pipeline = Ekorn::Pipeline->new(
in_workers(2, 'My::Years::look_up',
init => 'My::Years::no_table',
),
);
eval { $pipeline->(qw(Abba Blur)) };
print $@;
# Pipeline stage #1 failed at ...
# in_workers couldn't set up a worker: no table today at ...
The fix is in init: make it succeed, or die with a message saying what to do, as a reader will see only that.
Where next
Give init what it needs, with init_args.
Give init what it needs, with init_args
The problem
The table is in a file, and your program knows where. You'd like each worker to load the file your program names.
You'll need
Ekorn::Pipeline::Workers, as before.
The program
Save this module as lib/My/Years.pm:
package My::Years;
use v5.36;
# Load the table from the file the program names: a name and a year to
# a line, with a tab between.
sub load_file ($path) {
open my $in, '<', $path or die "Can't read $path: $!\n";
my %year = map { chomp; split m( \t )x } <$in>;
close $in;
return \%year;
}
sub look_up ($name, $table) {
return "$$ found $name, formed $table->{$name}";
}
1;
Then save this program as init-args.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use File::Temp qw(tempdir);
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
# A file to try it with. Use your own.
my $path = tempdir(CLEANUP => 1) . '/years.txt';
open my $out, '>', $path or die "Can't write $path: $!";
print {$out} "Abba\t1972\nBlur\t1988\nCream\t1966\n";
close $out;
my $pipeline = Ekorn::Pipeline->new(
in_workers(2, 'My::Years::look_up',
init => 'My::Years::load_file',
init_args => [$path],
),
);
say for $pipeline->(qw(Abba Blur Cream));
# ... found Abba, formed 1972
# ... found Blur, formed 1988
# ... found Cream, formed 1966
How it works
init_args => [$path] is a list of what to give init, in an array reference. Each worker is sent a copy, and calls load_file($path) with it, as it starts.
A worker can't read your program's variables, as the primer showed, so init_args is how a setting gets from your program to the workers: a file's path, a database's name, a user name and password.
What can go wrong
What init_args holds is copied to each worker, so it must be plain data, as a value must. Give it the open file in place of its path, and the run fails before any worker is set up:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
# A mistake: an open file, which can't be copied to a worker.
open my $in, '<', $0 or die "Can't read $0: $!";
my $pipeline = Ekorn::Pipeline->new(
in_workers(2, 'My::Years::look_up',
init => 'My::Years::load_file',
init_args => [$in],
),
);
eval { $pipeline->(qw(Abba Blur)) };
print $@;
# Pipeline stage #1 failed at ...
# in_workers can't send its init_args to a worker: Can't store GLOB items at ...
The fix is to send the path, and let each worker open the file itself. The same goes for a database handle: send what to connect with, and let each worker connect, as chapter 3 does.
Where next
Tidy up as each worker leaves, with done.
Tidy up as each worker leaves, with done
The problem
Each worker opens something in init, such as a log or a connection, and you'd like it closed properly as the worker leaves.
You'll need
Ekorn::Pipeline::Workers, as before.
The program
Save this module as lib/My/Logged.pm:
package My::Logged;
use v5.36;
# Open a log of this worker's own, in the folder the program names.
sub open_log ($folder) {
open my $log, '>', "$folder/$$.log" or die "Can't write the log: $!\n";
return $log;
}
# Note each name in the log, and pass it on.
sub look_up ($name, $log) {
say {$log} "looked up $name";
return "$$ found $name";
}
# Say goodbye, and close the log, as the worker leaves.
sub close_log ($log) {
say {$log} 'goodbye';
close $log or die "Can't close the log: $!\n";
return;
}
1;
Then save this program as done.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use File::Temp qw(tempdir);
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
my $folder = tempdir(CLEANUP => 1);
my $pipeline = Ekorn::Pipeline->new(
in_workers(2, 'My::Logged::look_up',
init => 'My::Logged::open_log',
init_args => [$folder],
done => 'My::Logged::close_log',
),
);
my @found = $pipeline->(qw(Abba Blur Cream Doves));
# Read every worker's log, once the run is over.
my @logs = glob "$folder/*.log";
say scalar(@logs), ' logs'; # 2 logs
for my $path (@logs) {
open my $in, '<', $path or die "Can't read $path: $!";
my @lines = <$in>;
close $in;
say 'a log ending ', $lines[-1] =~ s( \n \z )()xr;
}
# a log ending goodbye
# a log ending goodbye
How it works
init gives back the open log, which each worker keeps. It's never sent anywhere: it stays in the worker that opened it, so it needn't be something that can be copied.
look_up is given the log after each name, and writes to it.
done => 'My::Logged::close_log' names a function each worker runs as it leaves, once the run is over, given what init returned. Here it writes "goodbye" and closes the log, so both logs end with it.
What can go wrong
done runs when a worker leaves normally: the run is over, or a stage after this one stopped it, as take does, while the worker had nothing to do. A worker still busy when the run stops is ended at once, without its done, so as not to keep you waiting for work no one needs. Write done for tidying, never for work that must happen, such as saving results: those belong in the stages after, in your program.
Where next
Keep something in a worker from one value to the next.
Keep something in a worker from one value to the next
The problem
You'd like your function to remember something between the values a worker is given, such as how many it has done.
You'll need
Ekorn::Pipeline::Workers, as before.
The program
Save this module as lib/My/Counted.pm:
package My::Counted;
use v5.36;
# A count of this worker's own, starting at nothing.
sub start_count () {
return {done => 0};
}
sub look_up ($name, $count) {
$count->{done}++;
return "$$ found $name, its number $count->{done}";
}
1;
Then save this program as count.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
my $pipeline = Ekorn::Pipeline->new(
in_workers(1, 'My::Counted::look_up',
init => 'My::Counted::start_count',
),
);
say for $pipeline->(qw(Abba Blur Cream));
# ... found Abba, its number 1
# ... found Blur, its number 2
# ... found Cream, its number 3
How it works
init runs once, so the hash it returns is made once, and the worker passes that same hash to look_up with every name. A change look_up makes to it is still there for the next name.
There's one worker here, so it counts every name. With several, each has a hash of its own, and counts only the names it was sent.
What can go wrong
What a worker keeps is its own. Your program can't see it, other workers can't, and it's gone when the worker leaves at the end of the run. For a total across workers, return what you need with each result, and add them up in a stage after, in your program.
Where next
Chapter 3 connects each worker to a database.
3. Databases, with DBIx::Squirrel
A database query through the DBI stops your program until the answer comes. That's the work these stages are for: each worker runs its own queries, on its own connection, while the others run theirs.
The recipes use DBIx::Squirrel, a DBI wrapper that runs a query's rows through Ekorn stages, and SQLite, a database in a file, so they run anywhere. With your own database, only the connection details change.
Run slow queries side by side, each worker connecting for itself
Send rows to the workers, and write the results back in your program
Run slow queries side by side, each worker connecting for itself
The problem
You have a list of names, and a query to run for each, which takes a second. One after another, they take a second each. You'd like them run side by side, each on a connection of its own.
You'll need
Ekorn::Pipeline::Workers, DBIx::Squirrel, and DBD::SQLite, for the database in the recipe:
cpanm Ekorn::Pipeline::Workers DBIx::Squirrel DBD::SQLite
The program
Save this module as lib/My/Bands.pm:
package My::Bands;
use v5.36;
use DBIx::Squirrel;
# Connect, once in each worker, as it starts.
sub connect_to ($dsn) {
my $dbh = DBIx::Squirrel->connect($dsn, '', '', {RaiseError => 1});
# SQLite answers at once, so this gives it a function, pause, that
# waits, to stand in for a busy server. Leave it out for yours.
$dbh->sqlite_create_function('pause', 1, sub ($seconds) { sleep $seconds });
return $dbh;
}
# A query for one name, on this worker's connection.
sub formed ($name, $dbh) {
my $band = $dbh->selectrow_hashref(
'SELECT formed, pause(1) FROM band WHERE name = ?', undef, $name,
);
return "$$ found $name, formed $band->{formed}";
}
# Disconnect, as the worker leaves.
sub disconnect ($dbh) {
$dbh->disconnect;
return;
}
1;
Then save this program as queries.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use File::Temp qw(tempdir);
use Time::HiRes qw(time);
use DBIx::Squirrel;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
# A database to try it with, in a file. Use your own.
my $dsn = 'dbi:SQLite:dbname=' . tempdir(CLEANUP => 1) . '/music.db';
my $dbh = DBIx::Squirrel->connect($dsn, '', '', {RaiseError => 1});
$dbh->do('CREATE TABLE band (name TEXT, formed INTEGER)');
$dbh->do('INSERT INTO band VALUES (?, ?)', undef, @$_)
for ['Abba', 1972], ['Blur', 1988], ['Cream', 1966];
$dbh->disconnect;
my $pipeline = Ekorn::Pipeline->new(
in_workers(3, 'My::Bands::formed',
init => 'My::Bands::connect_to',
init_args => [$dsn],
done => 'My::Bands::disconnect',
),
);
my $started = time;
say for $pipeline->(qw(Abba Blur Cream));
# ... found Abba, formed 1972
# ... found Blur, formed 1988
# ... found Cream, formed 1966
printf "took %d s\n", time - $started; # took 1 s
How it works
The program makes the database, then disconnects. It sends the workers only $dsn, the string that says where the database is, in init_args.
Each worker connects for itself, in init, and keeps the handle for its run. formed is given that handle after each name, and runs the query on it. So three queries run at once, on three connections, and the three seconds of waiting take one. done disconnects each, as the run ends.
With your own database, $dsn is its data source, such as dbi:Pg:dbname=music, and the user name and password go in init_args too.
What can go wrong
Don't send a worker your program's own handle. It can't be copied, and a connection mustn't be shared between processes in any case:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use DBIx::Squirrel;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
my $dbh = DBIx::Squirrel->connect('dbi:SQLite:dbname=:memory:', '', '', {RaiseError => 1});
# A mistake: the program's handle, sent to the workers.
my $pipeline = Ekorn::Pipeline->new(
in_workers(2, 'My::Bands::formed',
init => 'My::Bands::connect_to',
init_args => [$dbh],
),
);
eval { $pipeline->(qw(Abba Blur)) };
print $@;
# Pipeline stage #1 failed at ...
# in_workers can't send its init_args to a worker: Can't store CODE items at ...
The fix is the recipe's: send what to connect with, and let each worker connect. Your program's handle is safe while the workers run, as no worker has a copy of it to close.
Each worker is a connection, so ask for no more workers than your database will take connections, leaving room for everything else that connects to it.
Where next
Send rows to the workers, and write the results back in your program.
Send rows to the workers, and write the results back in your program
The problem
A table needs a column filled in, row by row, by work that takes a second a row: a call to a slow service, say. You'd like the work done side by side, and the answers written back to the table.
You'll need
Ekorn::Pipeline::Workers, DBIx::Squirrel and DBD::SQLite, as before.
The program
Save this module as lib/My/Lengths.pm:
package My::Lengths;
use v5.36;
my %seconds = (Parklife => 187, Waterloo => 164, 'White Room' => 298);
# Find a track's length, from its row. The sleep stands in for a slow
# service. It gives back what the program needs to write the answer.
sub length_of ($track) {
sleep 1;
return {id => $track->{id}, length => $seconds{ $track->{title} }};
}
1;
Then save this program as fill-in.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use DBIx::Squirrel;
use Ekorn::Pipeline::Workers qw(in_workers);
# A database to try it with, with no lengths yet. Use your own.
my $dbh = DBIx::Squirrel->connect('dbi:SQLite:dbname=:memory:', '', '', {RaiseError => 1});
$dbh->do('CREATE TABLE track (id INTEGER PRIMARY KEY, title TEXT, length INTEGER)');
$dbh->do('INSERT INTO track (title) VALUES (?)', undef, $_)
for 'Parklife', 'Waterloo', 'White Room';
# Write a track's length back, here, in the program.
sub save ($found) {
$dbh->do('UPDATE track SET length = ? WHERE id = ?', undef, $found->{length}, $found->{id});
return $found->{id};
}
my @saved = $dbh->iterate(
'SELECT id, title FROM track WHERE length IS NULL',
{ekorn_slice => {}},
in_workers(3, 'My::Lengths::length_of'),
\&save,
)->all;
say scalar(@saved), ' rows filled in'; # 3 rows filled in
for my $track (@{ $dbh->selectall_arrayref('SELECT title, length FROM track ORDER BY id') }) {
say "$track->[0]: $track->[1] s";
}
# Parklife: 187 s
# Waterloo: 164 s
# White Room: 298 s
How it works
$dbh->iterate($sql, @stages) runs the query, and passes each row through the stages after it. {ekorn_slice => {}} asks for each row as a hash, {id => 1, title => 'Parklife'}, which is what crosses to a worker best, as the next recipe says.
in_workers sends each row to a worker, a copy, as always, and length_of gives back the row's id and its length. \&save is an ordinary stage after it, in the program, which writes each answer with an UPDATE. ->all runs it all.
So the workers never touch the database. Only the slow work is theirs; the reading and writing stay in the program, on its one connection. That keeps every write in one place, in one order, which matters for SQLite, where only one connection may write at a time, and makes a transaction around the writes possible, on any database.
This program needs no init, as the workers need no connection. When the work itself is a query, as in the recipe before, each worker connects for itself.
What can go wrong
The rows come from a query that's still running while save writes: DBIx::Squirrel reads them a few at a time. That's fine on SQLite and most databases, on the same connection. If yours objects, read the rows first, with ->all, then run the pipeline over them.
Where next
Send rows as hashes, not objects.
Send rows as hashes, not objects
The problem
DBIx::Squirrel's results gives each row as an object, with a method for each column, such as $row->title. You'd like to use those methods in a worker.
You'll need
Ekorn::Pipeline::Workers, DBIx::Squirrel and DBD::SQLite, as before.
The program
Save this module as lib/My/Titles.pm:
package My::Titles;
use v5.36;
# Shout a track's title, from its row, given as a hash.
sub shout ($track) {
return uc $track->{title};
}
1;
Then save this program as hashes.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use DBIx::Squirrel;
use Ekorn::Pipeline::Workers qw(in_workers);
# A database to try it with. Use your own.
my $dbh = DBIx::Squirrel->connect('dbi:SQLite:dbname=:memory:', '', '', {RaiseError => 1});
$dbh->do('CREATE TABLE track (title TEXT)');
$dbh->do('INSERT INTO track VALUES (?)', undef, $_) for 'Parklife', 'Waterloo';
say for $dbh->iterate(
'SELECT title FROM track',
{ekorn_slice => {}},
in_workers(2, 'My::Titles::shout'),
)->all;
# PARKLIFE
# WATERLOO
How it works
A row as a hash is plain data, so its copy in the worker is just like the original: $track->{title} works there as here.
A row object from results is different. Its class, with the method for each column, is made by DBIx::Squirrel as the query runs, in your program. A worker never ran the query, so the copy it gets is an object of a class with no methods.
What can go wrong
Send a worker a row from results, and calling a column's method there fails. To see it, save this as lib/My/Titles.pm, in place of the module above:
package My::Titles;
use v5.36;
# A mistake: a column's method, on a row object from results.
sub shout ($track) {
return uc $track->title;
}
1;
Then run this:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use DBIx::Squirrel;
use Ekorn::Pipeline::Workers qw(in_workers);
my $dbh = DBIx::Squirrel->connect('dbi:SQLite:dbname=:memory:', '', '', {RaiseError => 1});
$dbh->do('CREATE TABLE track (title TEXT)');
$dbh->do('INSERT INTO track VALUES (?)', undef, 'Parklife');
eval { $dbh->results('SELECT title FROM track', in_workers(2, 'My::Titles::shout'))->all };
print $@;
# Pipeline stage #1 failed at ...
# Can't locate object method "title" via package "DBIx::Squirrel::Result::Row_..." at ...
The fix is the recipe's: read the rows with iterate, as hashes, or send the worker only the columns it needs.
Where next
Chapter 4 looks each key up only once, however many rows share it.
4. Look each key up once, with once_per
Often many values share what you look up: tracks by the same artist, orders from the same customer, lines of a log from the same address. Looking the same thing up again wastes a worker. once_per looks up each key once, and gives every value that shares it the same answer.
Look each artist up once, for all their tracks
The problem
You have a list of tracks, several by each artist, and you'd like each track's artist's country, which takes a second to look up. Looking it up for every track would look up each artist many times.
You'll need
Ekorn::Pipeline::Workers:
cpanm Ekorn::Pipeline::Workers
The program
Save this module as lib/My/Country.pm:
package My::Country;
use v5.36;
my %from = (Abba => 'Sweden', Blur => 'England');
# Look an artist's country up: a second each, as a slow service might
# take. It gives the number of the process it ran in, too.
sub of ($artist) {
sleep 1;
return "$from{$artist}, found by $$";
}
1;
Then save this program as once.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Time::HiRes qw(time);
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(once_per);
my @tracks = (
{title => 'Waterloo', artist => 'Abba'},
{title => 'Parklife', artist => 'Blur'},
{title => 'Dancing Queen', artist => 'Abba'},
{title => 'Song 2', artist => 'Blur'},
{title => 'SOS', artist => 'Abba'},
);
my $pipeline = Ekorn::Pipeline->new(
once_per(
sub ($track) { $track->{artist} },
2,
'My::Country::of',
join => sub ($track, $country) { "$track->{title}: $country" },
),
);
my $started = time;
say for $pipeline->(@tracks);
# Waterloo: Sweden, found by ...
# Parklife: England, found by ...
# Dancing Queen: Sweden, found by ...
# Song 2: England, found by ...
# SOS: Sweden, found by ...
printf "%d tracks in %d s\n", scalar @tracks, time - $started; # 5 tracks in 1 s
How it works
once_per takes four things:
The key, a code reference, given each value: here the track's artist. It runs in your program, so it can be any code, a block included.
How many workers, as for
in_workers.The function, which runs in a worker, given a key, never a value: here
My::Country::of, given "Abba" or "Blur".**
join,** a code reference, given each value and its key's answer, which makes what the stage passes on. It runs in your program too.
So there are five tracks but only two artists, and only two look-ups, one for each, side by side: the whole run takes one second. Every Abba track has the same answer, from the same process, as it was looked up once and kept.
A key asked for again while its look-up is still running, as Abba is for Dancing Queen, waits for that look-up, rather than starting another. The tracks come out in the order they went in.
Keys are kept, with their answers, for the run, and forgotten at its end. A track waiting for its key's answer is held, up to 1,000 by default, after which the stage waits for answers before taking more; hold => 5000, among the options, changes that.
What can go wrong
The key must be defined. A track with no artist has no key, and the run fails, naming the line that ran the pipeline:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(once_per);
my $pipeline = Ekorn::Pipeline->new(
once_per(sub ($track) { $track->{artist} }, 2, 'My::Country::of'),
);
eval { $pipeline->({title => 'Untitled'}) };
print $@;
# Pipeline stage #1 failed at ...
# Expected a key for each value, not undef at ...
The fix is to give every value a key, or to drop those without one in a stage before, such as sub ($track) { defined $track->{artist} ? $track : () }.
Where next
Get only the answers, with no join.
Get only the answers, with no join
The problem
You have a list of names with repeats, and you'd like each one's answer, looked up once a name, without the values themselves.
You'll need
Ekorn::Pipeline::Workers, as before.
The program
Save this module as lib/My/Country.pm:
package My::Country;
use v5.36;
my %from = (Abba => 'Sweden', Blur => 'England');
sub of ($artist) {
sleep 1;
return "$artist is from $from{$artist}";
}
1;
Then save this program as answers.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(once_per);
my $pipeline = Ekorn::Pipeline->new(
once_per(sub ($name) { $name }, 2, 'My::Country::of'),
);
say for $pipeline->(qw(Abba Blur Abba));
# Abba is from Sweden
# Blur is from England
# Abba is from Sweden
How it works
Without a join, each value becomes its key's answer. The key here is the name itself, sub ($name) { $name }, so each name becomes what of said for it.
Abba comes twice, and is looked up once: the second Abba gets the same answer as the first.
What can go wrong
Leaving out join drops the values, so an answer can't tell you which value it was for, unless it says so itself, as of does here. When you need the value too, give a join, as the recipe before does.
Where next
Keep values that can't be copied.
Keep values that can't be copied
The problem
Your values hold something that can't be sent to a worker, such as a code reference, an open file or an object with a connection inside. You'd still like the slow look-ups done in workers.
You'll need
Ekorn::Pipeline::Workers, as before.
The program
Save this module as lib/My/Country.pm:
package My::Country;
use v5.36;
my %from = (Abba => 'Sweden', Blur => 'England');
sub of ($artist) {
sleep 1;
return $from{$artist};
}
1;
Then save this program as keep.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(once_per);
# Each track carries a code reference, which no worker could be sent.
my @tracks = (
{title => 'Waterloo', artist => 'Abba', shout => sub ($text) { uc $text }},
{title => 'Parklife', artist => 'Blur', shout => sub ($text) { uc $text }},
);
my $pipeline = Ekorn::Pipeline->new(
once_per(
sub ($track) { $track->{artist} },
2,
'My::Country::of',
join => sub ($track, $country) { $track->{shout}->("$track->{title} from $country") },
),
);
say for $pipeline->(@tracks);
# WATERLOO FROM SWEDEN
# PARKLIFE FROM ENGLAND
How it works
once_per sends a worker only the key: here, the artist's name, a string. The track itself never leaves your program. The key and join run in your program, so join can use anything the track holds, such as its code reference.
So once_per suits values that are big, or can't be copied, as long as what the look-up needs fits in a key. With in_workers, the whole value goes to the worker, and a track like these would fail, as What a worker is given is a copy showed.
What can go wrong
The key is still sent, so it must be something that can be copied: a string or a number, as here, or plain data. And as it's the key that decides what's looked up once, two values the look-up treats alike must give the same key: "Abba" and "ABBA" are two keys, and two look-ups.
Where next
Look each key up in a database, once.
Look each key up in a database, once
The problem
Each of many orders names a customer, and you'd like each customer's details from the database: one slow query per customer, not per order, and several at once.
You'll need
Ekorn::Pipeline::Workers, DBIx::Squirrel and DBD::SQLite:
cpanm Ekorn::Pipeline::Workers DBIx::Squirrel DBD::SQLite
The program
Save this module as lib/My/Customers.pm:
package My::Customers;
use v5.36;
use DBIx::Squirrel;
# Connect, once in each worker, as it starts.
sub connect_to ($dsn) {
my $dbh = DBIx::Squirrel->connect($dsn, '', '', {RaiseError => 1});
# A function that waits, to stand in for a busy server. Leave it out
# for yours.
$dbh->sqlite_create_function('pause', 1, sub ($seconds) { sleep $seconds });
return $dbh;
}
# A customer's details, by id: a plain hash, which can cross back.
sub details ($id, $dbh) {
return $dbh->selectrow_hashref(
'SELECT name, city, pause(1) AS waited FROM customer WHERE id = ?', undef, $id,
);
}
sub disconnect ($dbh) {
$dbh->disconnect;
return;
}
1;
Then save this program as customers.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use File::Temp qw(tempdir);
use Time::HiRes qw(time);
use DBIx::Squirrel;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(once_per);
# A database to try it with, in a file. Use your own.
my $dsn = 'dbi:SQLite:dbname=' . tempdir(CLEANUP => 1) . '/shop.db';
my $dbh = DBIx::Squirrel->connect($dsn, '', '', {RaiseError => 1});
$dbh->do('CREATE TABLE customer (id INTEGER PRIMARY KEY, name TEXT, city TEXT)');
$dbh->do('INSERT INTO customer (name, city) VALUES (?, ?)', undef, @$_)
for ['Ann', 'Leeds'], ['Bo', 'York'];
$dbh->disconnect;
my @orders = (
{number => 101, customer => 1},
{number => 102, customer => 2},
{number => 103, customer => 1},
{number => 104, customer => 1},
);
my $pipeline = Ekorn::Pipeline->new(
once_per(
sub ($order) { $order->{customer} },
2,
'My::Customers::details',
init => 'My::Customers::connect_to',
init_args => [$dsn],
done => 'My::Customers::disconnect',
join => sub ($order, $customer) {
"order $order->{number}: $customer->{name}, $customer->{city}";
},
),
);
my $started = time;
say for $pipeline->(@orders);
# order 101: Ann, Leeds
# order 102: Bo, York
# order 103: Ann, Leeds
# order 104: Ann, Leeds
printf "took %d s\n", time - $started; # took 1 s
How it works
This is chapter 3's way of connecting, with once_per's way of looking up. init, init_args and done work for once_per just as for in_workers: each worker connects as it starts, and disconnects as it leaves.
Four orders, two customers: two queries, side by side, so one second. details gives back the row as a hash, which crosses back to the program, where join puts it with each order.
What can go wrong
The answer, like a value, must be something that can cross: give back a hash or the columns you need, never a statement handle, and not a DBIx::Squirrel row object, as Send rows as hashes, not objects explains.
Where next
Chapter 5 puts Ekorn's own parts around the stages.
5. Ekorn's parts, around the stages
The stages are Ekorn stages, so everything else Ekorn::Pipeline has works around them, unchanged: sources that read values from files, stages that drop or stop, sinks that write results, and the context that says where each result came from. Those parts run in your program; only the stage's function runs in the workers.
Every name the recipes import from Ekorn comes from Ekorn::Pipeline::Tooling, which gathers them all. Ekorn::Pipeline's own guide, Ekorn::Pipeline::Manual::HowTo, says more about each.
Look up each name listed in a file
The problem
The names to look up are in a file, one to a line, maybe millions of them. You'd like them read as the work goes, never all at once.
You'll need
Ekorn::Pipeline::Workers:
cpanm Ekorn::Pipeline::Workers
The program
Save this module as lib/My/Slow.pm:
package My::Slow;
use v5.36;
use Time::HiRes qw(sleep);
# A look-up that takes a fifth of a second.
sub look_up ($name) {
sleep 0.2;
return "found $name";
}
1;
Then save this program as from-file.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
use Ekorn::Pipeline::Tooling qw(from_file);
# A file of names to try it with, one to a line. Use your own.
open my $out, '>', 'names.txt' or die "Can't write names.txt: $!\n";
print {$out} "Abba\nBlur\nCream\n";
close $out or die "Can't write names.txt: $!\n";
my $pipeline = Ekorn::Pipeline->new(
in_workers(3, 'My::Slow::look_up'),
);
say for $pipeline->iterator(from_file('names.txt'))->all;
# found Abba
# found Blur
# found Cream
How it works
from_file('names.txt') is a source: it reads the file a line at a time, and gives each line, without its newline, as a value. $pipeline->iterator($source) runs the pipeline over the source's values, and ->all gives every result.
The file is read as the stage asks for values. The stage takes a new one only when it has room, at most twice as many as it has workers, so a file of a million names is never all in memory.
What can go wrong
A file that's missing fails as the run starts, before any worker is started, with "Can't read names.txt: ...".
Where next
Skip what needn't reach a worker.
Skip what needn't reach a worker
The problem
Your file has blank lines and comments in it. Sending those to a worker would waste its time.
You'll need
Ekorn::Pipeline::Workers, as before.
The program
Save this module as lib/My/Slow.pm:
package My::Slow;
use v5.36;
use Time::HiRes qw(sleep);
# A look-up that takes a fifth of a second.
sub look_up ($name) {
sleep 0.2;
return "found $name";
}
1;
Then save this program as skip.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
use Ekorn::Pipeline::Tooling qw(drop_if from_file);
# A file to try it with, with a comment and a blank line. Use your own.
open my $out, '>', 'names.txt' or die "Can't write names.txt: $!\n";
print {$out} "# bands to look up\nAbba\n\nBlur\n";
close $out or die "Can't write names.txt: $!\n";
my $pipeline = Ekorn::Pipeline->new(
drop_if { m( \A \s* (?: \# | \z ) )x },
in_workers(2, 'My::Slow::look_up'),
);
say for $pipeline->iterator(from_file('names.txt'))->all;
# found Abba
# found Blur
How it works
drop_if { ... } is an ordinary stage, before the workers' stage. It drops each line its block is true for: here, a line that's blank or starts with #. It runs in your program, so it can be a block, and what it drops never goes to a worker.
Anything cheap to decide belongs in a stage before the workers: it costs microseconds in your program, where sending a value to a worker and back costs tens of them.
What can go wrong
Put the same check inside the function instead, and every line still crosses to a worker and back, for nothing. Only the work that's slow belongs in the workers.
Where next
Stop after the first few, and end the rest.
Stop after the first few, and end the rest
The problem
You only need the first two results. You'd like the run to stop once it has them, rather than finish the rest.
You'll need
Ekorn::Pipeline::Workers, as before.
The program
Save this module as lib/My/Slow.pm:
package My::Slow;
use v5.36;
# A look-up that takes a second.
sub look_up ($name) {
sleep 1;
return "found $name";
}
1;
Then save this program as first-two.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Time::HiRes qw(time);
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
use Ekorn::Pipeline::Tooling qw(take);
my $pipeline = Ekorn::Pipeline->new(
in_workers(2, 'My::Slow::look_up'),
take(2),
);
my $started = time;
say for $pipeline->(1 .. 10);
# found 1
# found 2
printf "took %d s, not 5\n", time - $started; # took 1 s, not 5
How it works
take(2) passes on two results, then stops the run. Ten values, two workers, a second each, would take five seconds in all. Here the first two are back after one, take stops the run, and the stage ends its workers at once: one that's idle leaves, running its done if it has one; one still busy with a value no one needs any more is ended where it is.
What can go wrong
A worker ended while busy doesn't finish its value, and doesn't run done. That's what you want for a look-up, but not for work that must finish once started, such as writing to a database: there, do the writing in a stage after, in your program, as chapter 3 does.
A stop ends the work only while values are still coming. Once they've run out, the stage finishes every value it still holds before it passes any on, so a stop after it ends nothing early. Here ten values keep coming past the two the stop wants; with only three, all three look-ups would finish, and the run would take two seconds.
Where next
Look up each row of a CSV file, and save the answers as CSV.
Look up each row of a CSV file, and save the answers as CSV
The problem
Your input is a CSV file, with a header, and you'd like a CSV file out, with an answer added to each row.
You'll need
Ekorn::Pipeline::Workers, and Text::CSV, which Ekorn::Pipeline uses for CSV:
cpanm Ekorn::Pipeline::Workers Text::CSV
The program
Save this module as lib/My/Years.pm:
package My::Years;
use v5.36;
use Time::HiRes qw(sleep);
my %formed = (Abba => 1972, Blur => 1988);
# Add the year the artist formed to a row, given as a hash.
sub add_formed ($row) {
sleep 0.2;
return {%$row, formed => $formed{ $row->{artist} }};
}
1;
Then save this program as csv.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
use Ekorn::Pipeline::Tooling qw(from_csv to_csv);
# A CSV file to try it with. Use your own.
open my $out, '>', 'tracks.csv' or die "Can't write tracks.csv: $!\n";
print {$out} qq(Title,Artist\nParklife,Blur\n"Knowing Me, Knowing You",Abba\n);
close $out or die "Can't write tracks.csv: $!\n";
my $pipeline = Ekorn::Pipeline->new(
in_workers(2, 'My::Years::add_formed'),
to_csv(file => 'formed.csv', header => [qw(title artist formed)]),
);
my($written) = $pipeline->iterator(
from_csv(file => 'tracks.csv', header => 1, munge => 'lc'),
)->all;
say "$written rows written"; # 2 rows written
open my $in, '<', 'formed.csv' or die "Can't read formed.csv: $!\n";
print <$in>;
# title,artist,formed
# Parklife,Blur,1988
# "Knowing Me, Knowing You",Abba,1972
How it works
from_csv reads the file a row at a time. header => 1 takes the first line as the column names, and munge => 'lc' makes them lower case, so each row is a hash: {title => 'Parklife', artist => 'Blur'}. A hash is plain data, so it crosses to a worker as it is.
add_formed gives back a copy of the row with formed added.
to_csv is a sink, the last stage, which writes each result to formed.csv, the columns in the order header names, quoting a title with a comma in it. A pipeline ending in a sink gives what the sink gives: here, how many rows it wrote, the one result of ->all, so my($written) takes it from the list.
What can go wrong
The sink writes in your program, never in a worker, so one file gets every row, in order. Writing to the file from the function instead would have each worker write to it at once, mixing the rows up.
Where next
Save the results as JSON Lines.
Save the results as JSON Lines
The problem
Your results are records, and you'd like them saved so that another program can read them back: one JSON object to a line.
You'll need
Ekorn::Pipeline::Workers, as before.
The program
Save this module as lib/My/Years.pm:
package My::Years;
use v5.36;
use Time::HiRes qw(sleep);
my %formed = (Abba => 1972, Blur => 1988);
# Give an artist's record.
sub record_of ($artist) {
sleep 0.2;
return {artist => $artist, formed => $formed{$artist}};
}
1;
Then save this program as jsonl.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
use Ekorn::Pipeline::Tooling qw(to_jsonl);
my $pipeline = Ekorn::Pipeline->new(
in_workers(2, 'My::Years::record_of'),
to_jsonl(file => 'artists.jsonl', json => {canonical => 1}),
);
my $written = $pipeline->(qw(Abba Blur));
say "$written written"; # 2 written
open my $in, '<', 'artists.jsonl' or die "Can't read artists.jsonl: $!\n";
print <$in>;
# {"artist":"Abba","formed":1972}
# {"artist":"Blur","formed":1988}
How it works
to_jsonl writes each result as JSON, on a line of its own, and gives how many it wrote. json => {canonical => 1} sorts each object's keys, so the lines are the same every run.
The records the workers send back are hashes, which is what JSON writes best.
What can go wrong
A result JSON can't write, such as an object, fails as the sink meets it. Give back plain hashes and arrays, as for anything that crosses from a worker.
Where next
Know which value each result came from.
Know which value each result came from
The problem
With in_workers_as_ready, the results come in the order they're ready, and your function's result doesn't say which value it was for. You'd like to know.
You'll need
Ekorn::Pipeline::Workers, as before.
The program
Save this module as lib/My/Uneven.pm:
package My::Uneven;
use v5.36;
use Time::HiRes qw(sleep);
# Abba takes longest, Blur the least.
my %seconds = (Abba => 2, Blur => 0.2, Cream => 1);
sub look_up ($name) {
sleep $seconds{$name};
return "took $seconds{$name} s";
}
1;
Then save this program as original.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers_as_ready);
use Ekorn::Pipeline::Tooling qw(result_original);
my $pipeline = Ekorn::Pipeline->new(
in_workers_as_ready(3, 'My::Uneven::look_up'),
sub ($result) { result_original . " $result" },
);
say for $pipeline->(qw(Abba Blur Cream));
# Blur took 0.2 s
# Cream took 1 s
# Abba took 2 s
How it works
result_original, in a stage after the workers, gives the value the current result was made from, as it went into the pipeline. The workers' stages keep each value with its result, so even out of order, each result knows its own: Blur's is Blur's.
What can go wrong
result_original works in the function too, in a worker, as the stage sends where each value stands with it. But an original that can't be copied, such as one holding an open file, is left behind, and the function sees undef for it. The value the function is given is usually all it needs; ask for the original in a stage after.
Where next
Number the results
The problem
You'd like each result numbered, 1, 2, 3, in the order they come out.
You'll need
Ekorn::Pipeline::Workers, as before.
The program
Save this module as lib/My/Slow.pm:
package My::Slow;
use v5.36;
use Time::HiRes qw(sleep);
sub look_up ($name) {
sleep 0.2;
return "found $name";
}
1;
Then save this program as numbered.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
use Ekorn::Pipeline::Tooling qw(result_number);
my $pipeline = Ekorn::Pipeline->new(
in_workers(2, 'My::Slow::look_up'),
sub ($result) { result_number . ". $result" },
);
say for $pipeline->(qw(Abba Blur Cream));
# 1. found Abba
# 2. found Blur
# 3. found Cream
How it works
result_number gives the number of the result the stage is making: the results so far, plus one. In a stage after the workers, that's the order they come out, whichever worker made them.
What can go wrong
The number counts results, not values. A value the function gives nothing for isn't counted, and one it gives two for counts twice.
Where next
Chapter 6 is for when things go wrong.
6. When things go wrong
Work fails: a record is missing, a service refuses, a worker crashes. These recipes show what the stages do with each failure, and how to choose what happens instead. The rule throughout is Ekorn's own: a failure is passed on in its turn, after the results before it, as a plain stage's would be.
See a failure stop the run, in its turn
The problem
One of your look-ups fails. You'd like to know what happens to the results before it, and to the rest.
You'll need
Ekorn::Pipeline::Workers:
cpanm Ekorn::Pipeline::Workers
The program
Save this module as lib/My/Tracks.pm:
package My::Tracks;
use v5.36;
use Time::HiRes qw(sleep);
# Look a track up. Track 3 is missing.
sub look_up ($n) {
sleep 0.1;
die "no track $n\n" if $n == 3;
return "track $n";
}
1;
Then save this program as fails.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
use Ekorn::Pipeline::Tooling qw(peek);
my $pipeline = Ekorn::Pipeline->new(
in_workers(2, 'My::Tracks::look_up'),
peek { say "got $_" },
);
eval { $pipeline->(1 .. 6) };
print "failed: $@";
# got track 1
# got track 2
# failed: Pipeline stage #1 failed at ...
# no track 3
How it works
peek { ... } sees each result go by, and passes it on unchanged: here it says what got past the workers' stage.
Track 3's look-up dies in its worker. The stage sends the error back, and throws it in the program in its turn: after tracks 1 and 2, which have already gone on, and before anything after it. The run ends there, the workers with it, and no track after 3 goes on, even those already looked up.
Ekorn wraps the error, as it does for any stage, saying which stage failed and where the pipeline was run, then the function's own message.
What can go wrong
Nothing more here, but stopping everything for one missing track is often not what you want. The next recipe keeps going.
Where next
Keep going: turn each failure into a result.
Keep going: turn each failure into a result
The problem
A missing track shouldn't stop the run. You'd like every track that's there, and a note of each that isn't.
You'll need
Ekorn::Pipeline::Workers, as before.
The program
Save this module as lib/My/Tracks.pm:
package My::Tracks;
use v5.36;
use experimental qw(try);
use Time::HiRes qw(sleep);
sub look_up ($n) {
sleep 0.1;
die "no track $n\n" if $n == 3;
return "track $n";
}
# Look a track up, and give back either the track or the failure, as a
# hash, so no failure leaves the worker.
sub look_up_safely ($n) {
try {
return {n => $n, track => look_up($n)};
}
catch ($error) {
chomp $error;
return {n => $n, error => $error};
}
}
1;
Then save this program as keep-going.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
my $pipeline = Ekorn::Pipeline->new(
in_workers(2, 'My::Tracks::look_up_safely'),
);
for my $result ($pipeline->(1 .. 4)) {
say $result->{error} // $result->{track};
}
# track 1
# track 2
# no track 3
# track 4
How it works
look_up_safely catches the failure in the worker, with try and catch, and gives it back as a result, a hash with an error key. Nothing dies, so the stage sees four ordinary results, and the run goes on to the end. Your program tells them apart by the key.
use experimental qw(try) turns on try and catch without a warning, as they're still marked experimental on the Perls this guide supports.
What can go wrong
Catch only what you expect. A failure that means something is really wrong, such as a lost database connection, is better left to stop the run, or every value after it fails too, one at a time.
Where next
Catch an error object by its class.
Catch an error object by its class
The problem
Your look-ups die with an exception object, of a class of your own, and you'd like to catch that class in your program, as you would if the work weren't in workers.
You'll need
Ekorn::Pipeline::Workers, as before.
The program
Save this module as lib/My/Tracks.pm:
package My::Tracks;
use v5.36;
# An exception of our own: a track that isn't there.
package My::Tracks::Missing {
sub new ($class, $n) { return bless {n => $n}, $class }
sub n ($self) { return $self->{n} }
}
sub look_up ($n) {
die My::Tracks::Missing->new($n) if $n == 3;
return "track $n";
}
1;
Then save this program as by-class.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
use My::Tracks ();
my $pipeline = Ekorn::Pipeline->new(
in_workers(2, 'My::Tracks::look_up'),
);
my @tracks = eval { $pipeline->(1 .. 4) };
if ($@ isa My::Tracks::Missing) {
say 'track ', $@->n, ' is missing'; # track 3 is missing
}
How it works
The object dies in a worker, and crosses back the way a value does, as a copy. The stage throws the copy in your program, as it was: Ekorn doesn't wrap an object, so $@ is the object itself, and isa finds its class.
use My::Tracks () loads the class in your program too. The copy keeps its class's name, but its methods, such as n, come from the class your program loaded.
What can go wrong
An object that can't be copied, such as one holding an open file, can't cross. The stage gives its message instead, as a string, as "$@" would show it. If your program matches on the class, give your exceptions plain data inside.
Where next
Stop the run from inside the function.
Stop the run from inside the function
The problem
Your function can tell when there's no point going on, such as when it finds what you were looking for. You'd like it to stop the run, not fail it.
You'll need
Ekorn::Pipeline::Workers, as before.
The program
Save this module as lib/My/Search.pm:
package My::Search;
use v5.36;
use Ekorn::Pipeline::Stop qw(Stop);
# Look through a page of results, and stop the run on finding Waterloo.
sub search ($page) {
return Stop("found Waterloo on page $page") if $page == 3;
return "nothing on page $page";
}
1;
Then save this program as stop.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
my $pipeline = Ekorn::Pipeline->new(
in_workers(2, 'My::Search::search'),
);
say for $pipeline->(1 .. 10);
# nothing on page 1
# nothing on page 2
# found Waterloo on page 3
How it works
Stop(...), from Ekorn::Pipeline::Stop, stops the run, passing on what it's given as its last results. It's not an error: the run ends normally, and gives what it got.
In a worker, the stop crosses back like a result, and the stage stops the run in its turn: after pages 1 and 2, with page 3's message, and nothing after it, though other workers may already have searched pages 4 and 5. Their answers are dropped, and the workers end.
What can go wrong
Stop dies with the stop, so don't call it inside your own eval or try in the function, or you'll catch it yourself. Call it where it can reach the stage.
Where next
Know when a worker dies
The problem
Something kills a worker in the middle of a value: a library crashes, or calls exit. You'd like to know which value it was working on.
You'll need
Ekorn::Pipeline::Workers, as before.
The program
Save this module as lib/My/Fragile.pm:
package My::Fragile;
use v5.36;
# Value 2 ends the worker's whole perl, as a crash in a library would.
sub process ($n) {
exit 3 if $n == 2;
return "did $n";
}
1;
Then save this program as dies.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
my $pipeline = Ekorn::Pipeline->new(
in_workers(2, 'My::Fragile::process'),
);
eval { $pipeline->(1 .. 4) };
print $@;
# Pipeline stage #1 failed at ...
# in_workers lost worker ..., which exited, status ..., with value #2
How it works
A worker that goes without sending a result back can't say why, but the stage knows which value it had. So the run fails with that value's number, counted from 1, the worker's process number, and its exit status, in its turn, as an error in the function would be.
An exit in a worker ends only that worker's perl, a process of its own, never your program.
What can go wrong
What a worker prints goes to your program's output. When that's a file or a pipe, rather than your screen, perl holds it in the worker until it has a block of it, or leaves, so it can come out late, mixed with your program's. Give back what you'd print, as a result, and print it in your program, as every recipe here does.
Where next
Know what a failure at the end costs.
Know what a failure at the end costs
The problem
You've seen that results before a failure go on first. There's one case where they don't, and it's worth knowing when.
You'll need
Ekorn::Pipeline::Workers, as before.
The program
Save this module as lib/My/Tracks.pm:
package My::Tracks;
use v5.36;
use Time::HiRes qw(sleep);
# Look a track up. Track 3, the last, is missing.
sub look_up ($n) {
sleep 0.1;
die "no track $n\n" if $n == 3;
return "track $n";
}
1;
Then save this program as at-the-end.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
use Ekorn::Pipeline::Tooling qw(peek);
for my $stage (
['one at a time', in_workers(1, 'My::Tracks::look_up', window => 1)],
['three at once', in_workers(3, 'My::Tracks::look_up')],
) {
my($name, $workers) = @$stage;
my @seen;
my $pipeline = Ekorn::Pipeline->new(
$workers,
peek { push @seen, $_ },
);
eval { $pipeline->(1 .. 3) };
say "$name: ", scalar(@seen), ' went on before the failure';
}
# one at a time: 2 went on before the failure
# three at once: 0 went on before the failure
How it works
window => 1 lets the stage send only one value before it waits for its result, so with one worker, tracks 1 and 2 go on as each is given, and track 3's failure comes after them.
With three workers, all three tracks are still with the workers when the values run out. Then the stage's flush gives what's left, and a flush can't give some results and then die: the failure takes the results with it. That's a limit of every Ekorn stage that holds values back, not only these.
What can go wrong
This bites when the failure is in the last few values, about twice as many as you have workers. Catch failures in the function, as Keep going does, and no failure reaches the stage, so nothing is lost.
Where next
Chapter 7 measures what starting workers costs.
7. What starting workers costs
A worker is a whole new perl, so starting one isn't free. Knowing what it costs, and when it's paid, tells you when the stages are worth it. The numbers here are from a Mac, and from GitHub's Windows runners; yours will differ, so each recipe measures, and says only what's true wherever it runs.
Measure what starting costs
The problem
You'd like to know what starting workers costs on your computer, before any work is done.
You'll need
Ekorn::Pipeline::Workers:
cpanm Ekorn::Pipeline::Workers
The program
Save this module as lib/My/Quick.pm:
package My::Quick;
use v5.36;
# Work that takes no time at all, so only starting is measured.
sub same ($value) {
return $value;
}
1;
Then save this program as start.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Time::HiRes qw(time);
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
for my $workers (1, 4) {
my $pipeline = Ekorn::Pipeline->new(
in_workers($workers, 'My::Quick::same'),
);
my $started = time;
$pipeline->('one value');
printf "%d workers: %.0f ms\n", $workers, 1000 * (time - $started);
}
# 1 workers: ... ms
# 4 workers: ... ms
How it works
Each run has one value and no work, so its time is the workers' start, and their leaving. On a Mac it's about 13 milliseconds a worker: about 13 for one, and about 50 for four. On Windows, starting a perl is slower: four take a quarter to half a second there.
The workers start one after another, but are ready together: the stage waits for every one before it sends the first value. So the cost grows with the number of workers, and is paid once a run.
Each worker loads what your module loads, too. A module that loads a large library, or connects to a database in init, adds that to every worker's start: DBIx::Squirrel, connecting to SQLite, makes four workers take about 55 milliseconds on a Mac.
What can go wrong
The first run of a program can be slower than the rest, while the system reads perl and its modules from disk. Measure a few times before you decide.
Where next
Work out whether workers will pay.
Work out whether workers will pay
The problem
You know roughly how long each value's work takes, and how many values there are. You'd like to know, before you change anything, whether workers will save time.
You'll need
Ekorn::Pipeline::Workers, as before.
The program
Save this module as lib/My/Quick.pm:
package My::Quick;
use v5.36;
sub same ($value) {
return $value;
}
1;
Then save this program as will-it-pay.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Time::HiRes qw(time);
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
my $workers = 4;
# Measure the start, as the last recipe did.
my $started = time;
Ekorn::Pipeline->new(in_workers($workers, 'My::Quick::same'))->(1);
my $start = time - $started;
# Without workers, the work takes values times seconds. With them, the
# start, then a share of the work for each worker.
for my $job ([100, 0.01], [100, 0.00001]) {
my($values, $seconds) = @$job;
my $without = $values * $seconds;
my $with = $start + $without / $workers;
printf "%d values of %g s: %s\n", $values, $seconds,
$with < $without ? 'workers pay' : 'an ordinary stage is faster';
}
# 100 values of 0.01 s: workers pay
# 100 values of 1e-05 s: an ordinary stage is faster
How it works
This is the sum the stages make you do. Without workers, the work takes as long as all its values together. With them, you pay the start once, then the work is shared between the workers, as long as there are values enough to keep them all busy.
So a hundred values of 10 milliseconds, a second in all, take about a quarter of a second with four workers, plus the start: workers pay. A hundred values of 10 microseconds take a thousandth of a second without workers, far less than starting even one.
Sending a value to a worker and its result back costs too, about 32 microseconds on a Mac, which this leaves out: it matters only when the work for each value is about that small, when workers don't pay anyway.
What can go wrong
The sum assumes the work can run side by side. Work that waits on one thing, such as one database that answers one query at a time, or one disk, gains nothing from more workers, however long it takes. And work for the CPU gains only up to the number of cores your computer has.
Where next
See that an empty run starts nothing.
See that an empty run starts nothing
The problem
Sometimes there's nothing to do: the query gives no rows, or the file is empty. You'd like to know that you don't pay for workers then.
You'll need
Ekorn::Pipeline::Workers, as before.
The program
Save this module as lib/My/Started.pm:
package My::Started;
use v5.36;
# Leave a file behind for each worker that starts, in the folder the
# program names, so the program can count them.
sub note_start ($folder) {
open my $out, '>', "$folder/$$" or die "Can't write: $!\n";
close $out;
return;
}
sub same ($value) {
return $value;
}
1;
Then save this program as empty.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use File::Temp qw(tempdir);
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
for my $values ([], ['one']) {
my $folder = tempdir(CLEANUP => 1);
my $pipeline = Ekorn::Pipeline->new(
in_workers(4, 'My::Started::same',
init => 'My::Started::note_start',
init_args => [$folder],
),
);
$pipeline->(@$values);
my @started = glob "$folder/*";
say scalar(@$values), ' values: ', scalar(@started), ' workers started';
}
# 0 values: 0 workers started
# 1 values: 4 workers started
How it works
The stage starts its workers when the first value reaches it, not when the pipeline is made, nor when the run starts. A run with no values never reaches that point, so it starts none, and costs nothing.
What can go wrong
The reverse holds too: a run of one value starts every worker you asked for, though only one has work. If many of your runs are tiny, ask for fewer workers, or run once over them all, as the next recipe does.
Where next
Run once over many values, not once a value.
Run once over many values, not once a value
The problem
Your program calls the pipeline in a loop, once for each value. You'd like to know what that costs, against one run over them all.
You'll need
Ekorn::Pipeline::Workers, as before.
The program
Save this module as lib/My/Started.pm:
package My::Started;
use v5.36;
# Leave a file behind for each worker that starts.
sub note_start ($folder) {
open my $out, '>', "$folder/$$" or die "Can't write: $!\n";
close $out;
return;
}
sub same ($value) {
return $value;
}
1;
Then save this program as once.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use File::Temp qw(tempdir);
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
my @names = qw(Abba Blur Cream Doves Elbow);
for my $how ('a run for each', 'one run for all') {
my $folder = tempdir(CLEANUP => 1);
my $pipeline = Ekorn::Pipeline->new(
in_workers(2, 'My::Started::same',
init => 'My::Started::note_start',
init_args => [$folder],
),
);
if ($how eq 'a run for each') {
$pipeline->($_) for @names;
}
else {
$pipeline->(@names);
}
my @started = glob "$folder/*";
say "$how: ", scalar(@started), ' workers started';
}
# a run for each: 10 workers started
# one run for all: 2 workers started
How it works
Each run of the pipeline has its own workers, started at its first value and ended with it. Called five times, the pipeline starts two workers five times: ten workers, for five values. Called once, with all five, it starts two.
So give a pipeline all its values in one run: as a list, or from a source, as $pipeline->iterator(from_file($path))->all does in chapter 5.
A run doesn't keep its workers for the next, so that nothing one run left in a worker, such as a table loaded for one query, can surprise the next.
What can go wrong
A program that can't gather its values first, because each comes as it happens, such as lines from a socket, can still use one run: give the pipeline a source that waits for the next value, and the workers stay up for as long as the source keeps giving.
Where next
See work too small to pay
The problem
You'd like to see, with real numbers, what happens when the work is too small for workers.
You'll need
Ekorn::Pipeline::Workers, as before.
The program
Save this module as lib/My/Quick.pm:
package My::Quick;
use v5.36;
# Work that takes microseconds: doubling a number.
sub double ($n) {
return 2 * $n;
}
1;
Then save this program as too-small.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Time::HiRes qw(time);
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
use My::Quick ();
my @numbers = 1 .. 1000;
my $started = time;
my @plain = Ekorn::Pipeline->new(\&My::Quick::double)->(@numbers);
my $plain = time - $started;
$started = time;
my @in_workers = Ekorn::Pipeline->new(in_workers(4, 'My::Quick::double'))->(@numbers);
my $workers = time - $started;
say 'the same results: ', ("@plain" eq "@in_workers" ? 'yes' : 'no'); # the same results: yes
say 'the ordinary stage was faster: ', ($plain < $workers ? 'yes' : 'no');
# the ordinary stage was faster: yes
How it works
\&My::Quick::double as a stage of its own, with no workers, runs the function in your program: doubling a thousand numbers takes well under a millisecond. In four workers, each number crosses to a worker and back, tens of microseconds each, after the workers' start: tens of milliseconds in all.
Both give the same results, in the same order. Only the time differs, and here the workers lose.
What can go wrong
Batching can rescue small work: send a worker a hundred numbers at a time, as one value, and have the function do them all, so each crossing carries a hundred times the work. Batch small work shows how.
Where next
Chapter 8 puts workers to work for the CPU.
8. Work for the CPU
Some work doesn't wait on anything: it just takes the processor's time, such as counting, compressing or checksumming. One perl runs on one core at a time, however many your computer has. Each worker is a perl of its own, so each can have a core of its own.
The recipes use only modules that come with Perl, so they run anywhere with nothing to install but Ekorn::Pipeline::Workers.
Crunch numbers on several cores
The problem
Each value takes about half a second of pure computing. One after another, four take two seconds. You'd like them spread over your computer's cores.
You'll need
Ekorn::Pipeline::Workers:
cpanm Ekorn::Pipeline::Workers
The program
Save this module as lib/My/Primes.pm:
package My::Primes;
use v5.36;
# Count the primes below $n, the slow way, by trying every divisor: work
# that keeps one core busy, with no waiting.
sub count_below ($n) {
my $count = 0;
NUMBER: for my $i (2 .. $n - 1) {
for (my $d = 2; $d * $d <= $i; $d++) {
next NUMBER if $i % $d == 0;
}
$count++;
}
return "$count primes below $n";
}
1;
Then save this program as primes.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Time::HiRes qw(time);
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
my @limits = (200_000, 220_000, 240_000, 260_000);
my(%took, @counts);
for my $workers (1, 2) {
my $pipeline = Ekorn::Pipeline->new(
in_workers($workers, 'My::Primes::count_below'),
);
my $started = time;
@counts = $pipeline->(@limits);
$took{$workers} = time - $started;
}
say for @counts;
# 17984 primes below 200000
# 19618 primes below 220000
# 21221 primes below 240000
# 22837 primes below 260000
say '2 workers were faster: ', ($took{2} < $took{1} ? 'yes' : 'no');
# 2 workers were faster: yes
How it works
With one worker, the four counts run one after another, on one core, as they would without workers. With two, two run at once, each on a core of its own, and the whole takes about half as long, plus the workers' start.
This is where workers differ most from Ekorn::Pipeline::Futures. A Future lets one perl wait on many things at once, but it can't make one perl compute faster: work like this, with no waiting, gains nothing from Futures, and everything from workers.
How many workers to ask for: about as many as your computer has cores, or one fewer, to leave one for everything else. More than that can't run at once, so they only add their start. To see how many cores you have, nproc on Linux, sysctl -n hw.ncpu on macOS, or the NUMBER_OF_PROCESSORS variable on Windows tells you.
What can go wrong
The gain is only as big as the cores that are free. On a computer busy with other work, or a shared server, two workers may be little faster than one. Measure on the computer the work will run on.
Where next
Checksum many files
The problem
You have many files, and you'd like a checksum of each, to see later whether any has changed. Reading and checksumming big files takes the CPU, and the disk.
You'll need
Ekorn::Pipeline::Workers, as before. Digest::SHA comes with Perl.
The program
Save this module as lib/My/Checksum.pm:
package My::Checksum;
use v5.36;
use Digest::SHA;
# Read a file, in the worker, and give its path with the first part of
# its SHA-256 checksum.
sub of_file ($path) {
my $digest = Digest::SHA->new(256)->addfile($path)->hexdigest;
return substr($digest, 0, 16) . " $path";
}
1;
Then save this program as checksums.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
# Files to try it with, each holding a title. Use your own.
my @paths;
for my $title ('Waterloo', 'Parklife', 'White Room') {
my $path = lc($title =~ s( \s )(-)xr) . '.txt';
open my $out, '>:raw', $path or die "Can't write $path: $!\n";
print {$out} "$title\n";
close $out or die "Can't write $path: $!\n";
push @paths, $path;
}
my $pipeline = Ekorn::Pipeline->new(
in_workers(3, 'My::Checksum::of_file'),
);
say for $pipeline->(@paths);
# 1e3e35b48f49414e waterloo.txt
# 363f3e308b53ac85 parklife.txt
# dd5e9c35a3c9e761 white-room.txt
How it works
The program sends each worker a file's path, a short string, not the file. The worker opens and reads the file itself, and sends back only the checksum. So each crossing carries a few bytes, however big the file.
Each worker starts in the folder your program was in when it started the workers, so a relative path, such as waterloo.txt, means the same file in a worker as in your program.
The files are written with :raw, so that Windows writes the same bytes as Linux and macOS, and the checksums are the same everywhere.
What can go wrong
Sending a file's contents in place of its path works, but copies all of it to the worker, and through a socket, as well as reading it in your program. Send the path, and let the worker read.
Where next
Compress many files
The problem
You'd like to gzip many files, side by side, each beside the original.
You'll need
Ekorn::Pipeline::Workers, as before. IO::Compress::Gzip comes with Perl.
The program
Save this module as lib/My/Gzip.pm:
package My::Gzip;
use v5.36;
use IO::Compress::Gzip qw(gzip $GzipError);
# Compress a file to one beside it, ending .gz, and give that one's
# path.
sub compress ($path) {
gzip($path => "$path.gz") or die "Can't compress $path: $GzipError\n";
return "$path.gz";
}
1;
Then save this program as gzip.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use IO::Uncompress::Gunzip qw(gunzip $GunzipError);
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
# Files to try it with, each of a thousand lines. Use your own.
my @paths;
for my $n (1 .. 3) {
my $path = "log-$n.txt";
open my $out, '>', $path or die "Can't write $path: $!\n";
print {$out} "line $_ of log $n\n" for 1 .. 1000;
close $out or die "Can't write $path: $!\n";
push @paths, $path;
}
my $pipeline = Ekorn::Pipeline->new(
in_workers(3, 'My::Gzip::compress'),
);
# Check each compressed file holds what its original did.
for my $gz ($pipeline->(@paths)) {
gunzip($gz => \my $text) or die "Can't read $gz: $GunzipError\n";
my $lines = () = $text =~ m( \n )xg;
say "$gz: $lines lines, ", -s $gz < length $text ? 'smaller' : 'larger';
}
# log-1.txt.gz: 1000 lines, smaller
# log-2.txt.gz: 1000 lines, smaller
# log-3.txt.gz: 1000 lines, smaller
How it works
Each worker compresses its file and writes the result itself, then sends back only the new file's path. The program checks each, by reading it back with gunzip into a string, and counting its lines.
A worker writing its own file, beside the one it read, is safe: no two workers write the same file. It's writing to one shared file, or to the same database table, that wants the program, as chapter 5 says.
What can go wrong
A worker stopped while busy, as when a stage after this one stops the run, is ended where it is, and can leave a half-written .gz behind. If that matters, have the function write to a temporary name, and rename it once it's done: a rename is all or nothing.
Where next
Batch small work, so each crossing carries more.
Batch small work, so each crossing carries more
The problem
Your work for each value is small, microseconds, but there are a great many values. Chapter 7 showed workers losing to an ordinary stage on work like that. You'd still like it spread over your cores.
You'll need
Ekorn::Pipeline::Workers, as before.
The program
Save this module as lib/My/Squares.pm:
package My::Squares;
use v5.36;
# Square one number.
sub square ($n) {
return $n * $n;
}
# Square a batch of numbers, given as an array reference, and give back
# their squares.
sub square_all ($numbers) {
return map { $_ * $_ } @$numbers;
}
1;
Then save this program as batches.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Time::HiRes qw(time);
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
use Ekorn::Pipeline::Tooling qw(batch);
my @numbers = 1 .. 20_000;
my $started = time;
my @one_by_one = Ekorn::Pipeline->new(
in_workers(4, 'My::Squares::square'),
)->(@numbers);
my $one_by_one = time - $started;
$started = time;
my @batched = Ekorn::Pipeline->new(
batch(1000),
in_workers(4, 'My::Squares::square_all'),
)->(@numbers);
my $batched = time - $started;
say 'the same results: ', ("@one_by_one" eq "@batched" ? 'yes' : 'no'); # the same results: yes
say 'batches were faster: ', ($batched < $one_by_one ? 'yes' : 'no'); # batches were faster: yes
How it works
batch(1000), an Ekorn stage before the workers, gathers a thousand numbers into one array reference, and passes that on as one value. So twenty thousand numbers cross to the workers as twenty values, and square_all squares a thousand at a time.
Each crossing costs tens of microseconds, whatever it carries. One by one, that's paid twenty thousand times; in batches, twenty. The work is the same, and its results come back in the same order, each batch's squares one after another.
What can go wrong
A batch's results come back together, so the first result waits for its whole batch. And if one value in a batch fails, the whole batch's results are lost with it. Choose a batch big enough that each takes milliseconds, and no bigger.
Where next
Chapter 9 builds on the stages: functions that take them, and pipelines with names.
9. Building on it
Ekorn's idea is that a function can let its caller finish the job: it takes stages from its caller, and runs what it hands out through them. The workers' stages are stages like any other, so they fit inside such functions, named pipelines and pipelines used as stages, unchanged.
Write a function that works in workers, and let its caller finish the job
The problem
You're writing a function that looks names up in workers. One caller wants only some of the answers, another wants a count. You'd rather not write a function for each.
You'll need
Ekorn::Pipeline::Workers:
cpanm Ekorn::Pipeline::Workers
The program
Save this module as lib/My/Years.pm:
package My::Years;
use v5.36;
use Time::HiRes qw(sleep);
my %formed = (Abba => 1972, Blur => 1988, Cream => 1966, Doves => 1998);
sub formed ($name) {
sleep 0.2;
return {name => $name, formed => $formed{$name}};
}
1;
Then save this program as caller.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
use Ekorn::Pipeline::Tooling qw(count_items take_if);
# Look the names up, in four workers, and run each answer through the
# caller's stages.
sub look_up ($names, @stages) {
return Ekorn::Pipeline->new(
in_workers(4, 'My::Years::formed'),
@stages,
)->(@$names);
}
my @names = qw(Abba Blur Cream Doves);
say for look_up(
\@names,
take_if { $_->{formed} < 1980 },
sub ($band) { "$band->{name}, $band->{formed}" },
);
# Abba, 1972
# Cream, 1966
say scalar look_up(
\@names,
count_items,
);
# 4
How it works
look_up takes a list of names, and any stages after it. It builds a pipeline of the workers' stage, then the caller's, and runs it.
The first caller keeps the bands formed before 1980, with take_if, and formats each. The second only counts them, with count_items, a sink, which gives one number. look_up didn't change for either: it does its part, the look-ups in workers, and leaves the rest to them.
The caller's stages run in the program, so they can be blocks. Only My::Years::formed runs in the workers.
What can go wrong
A caller can't move its own stages into the workers through such a function, as they're code in the program. That's as it should be: the function decides what's worth a worker, and the caller decides what to do with the answers.
Where next
Return an iterator, so the caller can stop the work.
Return an iterator, so the caller can stop the work
The problem
Your function may be given a great many names, and a caller may want only the first few answers. You'd like the work to stop when the caller stops, not run through every name first.
You'll need
Ekorn::Pipeline::Workers, as before.
The program
Save this module as lib/My/Slow.pm:
package My::Slow;
use v5.36;
use Time::HiRes qw(sleep);
sub look_up ($n) {
sleep 0.2;
return "found $n";
}
1;
Then save this program as iterator.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Time::HiRes qw(time);
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
use Ekorn::Pipeline::Tooling qw(from_array take);
# An iterator of the answers, looked up three at a time, as they're
# wanted.
sub answers ($values, @stages) {
return Ekorn::Pipeline->new(
in_workers(3, 'My::Slow::look_up'),
@stages,
)->iterator(from_array(@$values));
}
my $started = time;
my $first_two = answers(
[1 .. 1000],
take(2),
);
say for $first_two->all;
# found 1
# found 2
printf "took %s\n", time - $started < 2 ? 'under 2 s, not 70' : 'too long';
# took under 2 s, not 70
How it works
->iterator(from_array(@$values)) doesn't run anything yet. It gives an iterator, which runs the pipeline as the caller asks for results. ->all asks for all of them, and take(2) stops the run after two.
The stage takes values from the source only as it has room, a few at a time, so when take stops the run, the source has given only a few of the thousand, and the workers end. A thousand look-ups of a fifth of a second each, three at a time, would take about seventy seconds.
What can go wrong
Giving back a list in place of an iterator would run all thousand first. When a caller may stop early, give back the iterator, and let it decide.
Where next
Make a stage for others to use.
Make a stage for others to use
The problem
You'd like to give other programmers a stage that checksums files in workers, so they can put it in their own pipelines without knowing the module and function behind it.
You'll need
Ekorn::Pipeline::Workers, as before.
The program
Save this module as lib/My/Stages.pm:
package My::Stages;
use v5.36;
use Carp qw(croak);
use Digest::SHA;
use Ekorn::Pipeline::Workers qw(in_workers);
# A stage giving each file's SHA-256 checksum, in $n workers.
sub checksums ($n = 4) {
croak "Expected a number of workers, not $n" unless $n =~ m( \A [1-9] \d* \z )x;
return in_workers($n, 'My::Stages::checksum_of');
}
# What each worker runs. It's in the same module, so loading the stage
# loads the function.
sub checksum_of ($path) {
return {path => $path, sha256 => Digest::SHA->new(256)->addfile($path)->hexdigest};
}
1;
Then save this program as stage.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Ekorn::Pipeline;
use My::Stages;
# A file to try it with. Use your own.
open my $out, '>:raw', 'waterloo.txt' or die "Can't write waterloo.txt: $!\n";
print {$out} "Waterloo\n";
close $out or die "Can't write waterloo.txt: $!\n";
my $pipeline = Ekorn::Pipeline->new(
My::Stages::checksums(2),
sub ($file) { substr($file->{sha256}, 0, 16) . " $file->{path}" },
);
say for $pipeline->('waterloo.txt'); # 1e3e35b48f49414e waterloo.txt
How it works
checksums is an ordinary function that gives back a stage: whatever in_workers gives, with the module and function filled in. A caller puts it in a pipeline as it would any stage, and never names My::Stages::checksum_of.
Keeping the function the workers run in the same module as the stage means that anyone who can load the stage can load the function, and so can every worker.
checksums checks its own argument, so a mistake is reported in the caller's words, as a stage of yours, rather than as one of in_workers'.
What can go wrong
The function a worker runs must be a named function in a module, never a closure, so a stage like this can't capture its caller's settings in a block, as a stage running in the program could. Pass them with init_args, as chapter 2 does, from the stage's own arguments.
Where next
Give a pipeline a name, and use it by name.
Give a pipeline a name, and use it by name
The problem
Several parts of your program look names up in the same way, with the same cleaning first. You'd like to define it once, by name.
You'll need
Ekorn::Pipeline::Workers, as before.
The program
Save this module as lib/My/Slow.pm:
package My::Slow;
use v5.36;
use Time::HiRes qw(sleep);
sub look_up ($name) {
sleep 0.2;
return "found $name";
}
1;
Then save this program as named.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
use Ekorn::Pipeline::Tooling qw(drop_if pipeline take);
# How names are looked up, everywhere in the program.
Ekorn::Pipeline->named(
look_up_names =>
drop_if { m( \A \s* \z )x },
in_workers(2, 'My::Slow::look_up'),
);
my @first = pipeline(
'look_up_names',
take(2),
)->(
'Abba',
'',
'Blur',
'Cream',
);
say for @first;
# found Abba
# found Blur
How it works
Ekorn::Pipeline->named(look_up_names => @stages) keeps a pipeline under a name. pipeline('look_up_names', take(2)) makes a new pipeline of the named one's stages, then take(2). The blank name is dropped before it reaches a worker, and the run stops after two.
Naming a pipeline doesn't start any workers: they start with each run, at its first value, as always.
What can go wrong
A name used before it's defined fails, with Ekorn's message saying so. Define named pipelines as the program starts, before anything uses them.
Where next
Use a pipeline as a stage
The problem
You have a pipeline that cleans names and looks them up in workers, and you'd like to use it as one step of a bigger pipeline.
You'll need
Ekorn::Pipeline::Workers, as before.
The program
Save this module as lib/My/Slow.pm:
package My::Slow;
use v5.36;
use Time::HiRes qw(sleep);
sub look_up ($name) {
sleep 0.2;
return "found $name";
}
1;
Then save this program as as-a-stage.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
use Ekorn::Pipeline::Tooling qw(take);
# Trim each name, and look it up.
my $clean_look_up = Ekorn::Pipeline->new(
sub ($name) { $name =~ s( \A \s+ | \s+ \z )()xgr },
in_workers(2, 'My::Slow::look_up'),
);
my $pipeline = Ekorn::Pipeline->new(
$clean_look_up,
sub ($found) { uc $found },
take(2),
);
say for $pipeline->(
' Abba',
'Blur ',
'Cream',
);
# FOUND ABBA
# FOUND BLUR
How it works
A pipeline given as a stage stands for its stages, in place. So $pipeline is the trimming, the workers, the upper-casing and take, one after another, and take stopping the run ends the workers, as it would if their stage were written out.
What can go wrong
Nothing here, but mind what's in workers when pipelines nest: each workers' stage has workers of its own, started when its first value reaches it, so two such stages in one pipeline run two sets at once.
Where next
Feed values in as they arrive.
Feed values in as they arrive
The problem
Your values don't come all at once: they arrive one at a time, from a queue or a socket, say. You'd like them looked up in workers as they come, without starting workers for each.
You'll need
Ekorn::Pipeline::Workers, as before.
The program
Save this module as lib/My/Started.pm:
package My::Started;
use v5.36;
# Leave a file behind for each worker that starts.
sub note_start ($folder) {
open my $out, '>', "$folder/$$" or die "Can't write: $!\n";
close $out;
return;
}
sub look_up ($name) {
return "found $name";
}
1;
Then save this program as feed.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use File::Temp qw(tempdir);
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
my $folder = tempdir(CLEANUP => 1);
my $pipeline = Ekorn::Pipeline->new(
in_workers(2, 'My::Started::look_up',
init => 'My::Started::note_start',
init_args => [$folder],
),
);
my $feed = $pipeline->feed;
my @found;
for my $name (qw(Abba Blur Cream)) {
# Each name arrives, and is pushed in. Some results may come back
# at once; the rest come later.
push @found, $feed->push($name);
}
push @found, $feed->close;
say for @found;
# found Abba
# found Blur
# found Cream
my @started = glob "$folder/*";
say scalar(@started), ' workers started, for three names'; # 2 workers started, for three names
How it works
$pipeline->feed starts a run that you push values into, one at a time, as they arrive. Each push gives back whatever results are ready by then, which may be none: the workers are still working. close ends the run, and gives back the rest.
The run lasts from the first push to the close, so its workers do too: two, started at the first name, for all three, however far apart the names arrive.
What can go wrong
A feed that's never closed never finishes its run, so its workers are kept waiting for more, and the results still with them are never given. Close every feed, as soon as there's nothing more to push.
Where next
Chapter 10 solves whole problems, start to finish.
10. Whole problems, start to finish
These recipes put the earlier chapters together, each solving a problem as a real program would, from where the values come from to where the results go.
One problem, three ways: an ordinary stage, Futures and Workers
The problem
Ekorn::Pipeline has two ways of doing many things at once, and you'd like to see, with your own eyes, which suits which work, before you choose.
You'll need
Ekorn::Pipeline::Workers, Ekorn::Pipeline::Futures, Future::AsyncAwait and IO::Async:
cpanm Ekorn::Pipeline::Workers Ekorn::Pipeline::Futures Future::AsyncAwait IO::Async
The program
Save this module as lib/My/Work.pm:
package My::Work;
use v5.36;
# Work that waits a second, as a query or a slow service would.
sub wait_a_second ($n) {
sleep 1;
return $n;
}
# Work that computes for about half a second, with no waiting: counting
# the primes below 250,000, the slow way.
sub compute ($n) {
my $count = 0;
NUMBER: for my $i (2 .. 250_000) {
for (my $d = 2; $d * $d <= $i; $d++) {
next NUMBER if $i % $d == 0;
}
$count++;
}
return $n;
}
1;
Then save this program as three-ways.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Future::AsyncAwait;
use IO::Async::Loop;
use Time::HiRes qw(time);
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);
use Ekorn::Pipeline::Workers qw(in_workers);
use My::Work ();
my $loop = IO::Async::Loop->new;
# The waiting, as Futures do it: a timer on the loop, in place of sleep.
async sub wait_a_second ($n) {
await $loop->delay_future(after => 1);
return $n;
}
# The computing, as Futures would have to: the same code, in the block.
async sub compute ($n) {
return My::Work::compute($n);
}
# Run four values through a stage, and give the seconds it took.
sub timed ($stage) {
my $started = time;
Ekorn::Pipeline->new($stage)->(1 .. 4);
return time - $started;
}
# The fastest of three runs, as a busy computer can slow any one.
sub fastest ($stage) {
my($best) = sort { $a <=> $b } map { timed($stage) } 1 .. 3;
return $best;
}
my %waiting = (
'an ordinary stage' => timed(\&My::Work::wait_a_second),
'Futures' => timed(in_futures(4, \&wait_a_second)),
'Workers' => timed(in_workers(4, 'My::Work::wait_a_second')),
);
for my $way ('an ordinary stage', 'Futures', 'Workers') {
printf "waiting, %s: %d s\n", $way, $waiting{$way};
}
# waiting, an ordinary stage: 4 s
# waiting, Futures: 1 s
# waiting, Workers: 1 s
my $alone = fastest(\&My::Work::compute);
my %faster = (
'Futures' => fastest(in_futures(4, \&compute)) < 0.8 * $alone,
'Workers' => fastest(in_workers(2, 'My::Work::compute')) < 0.8 * $alone,
);
for my $way ('Futures', 'Workers') {
say "computing, $way faster than an ordinary stage: ", ($faster{$way} ? 'yes' : 'no');
}
# computing, Futures faster than an ordinary stage: no
# computing, Workers faster than an ordinary stage: yes
How it works
The same four values go through each way, twice: once with work that waits, once with work that computes.
The times are in whole seconds, rounded down, as %d gives them, so that a fraction for starting workers doesn't show as a second. Each way's computing is timed as the fastest of three runs, as a busy computer can slow any one of them, and a way counts as faster when it takes under 0.8 of an ordinary stage's time.
Waiting: an ordinary stage waits for each in turn, four seconds. Futures start all four timers in one process, and wait on them together: one second. Workers sleep in four processes at once: one second too, plus their start. Both save the waiting. Futures do it with less, as nothing starts; Workers do it for work that can't be written to wait on a loop, such as a DBI query or a blocking module.
Computing: an ordinary stage computes each in turn. Futures do no better: an async sub with no await in it runs straight through, in your one process, one value after another. Workers compute on two cores at once, and take about half as long.
So the split between the two distributions is what the work waits for:
Waits on I/O a library can wait on asynchronously, such as Mojo::UserAgent or IO::Async: Ekorn::Pipeline::Futures.
Blocks, or computes: Ekorn::Pipeline::Workers.
Neither, as it's quick: an ordinary stage.
What can go wrong
The times are your computer's. On one with a single free core, the workers can't compute faster either, and the last line says no. That's the lesson too: Workers can only use the cores there are.
Where next
Fetch, then compute: Futures feeding Workers.
Fetch, then compute: Futures feeding Workers
The problem
Your work has two halves: fetch something, which waits on the network, then compute on it, which keeps the CPU busy. You'd like each half done the way that suits it.
You'll need
Ekorn::Pipeline::Workers, Ekorn::Pipeline::Futures, Future::AsyncAwait and IO::Async, as before.
The program
Save this module as lib/My/Primes.pm:
package My::Primes;
use v5.36;
# Count the primes below a page's limit, the slow way: the computing
# half, for the workers.
sub of_page ($page) {
my $count = 0;
NUMBER: for my $i (2 .. $page->{limit} - 1) {
for (my $d = 2; $d * $d <= $i; $d++) {
next NUMBER if $i % $d == 0;
}
$count++;
}
return "$page->{name}: $count primes";
}
1;
Then save this program as fetch-compute.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Future::AsyncAwait;
use IO::Async::Loop;
use Time::HiRes qw(time);
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);
use Ekorn::Pipeline::Workers qw(in_workers);
my $loop = IO::Async::Loop->new;
# The fetching half. This stands in for a web request, which waits a
# second, then gives a page: here, a name and a number to count to.
async sub fetch ($n) {
await $loop->delay_future(after => 1);
return {name => "page $n", limit => 200_000 + 10_000 * $n};
}
my $pipeline = Ekorn::Pipeline->new(
in_futures(4, \&fetch),
in_workers(2, 'My::Primes::of_page'),
);
my $started = time;
say for $pipeline->(1 .. 4);
# page 1: 18807 primes
# page 2: 19618 primes
# page 3: 20437 primes
# page 4: 21221 primes
say 'faster than one at a time: ', (time - $started < 4 ? 'yes' : 'no');
# faster than one at a time: yes
How it works
The pipeline has two stages, one for each half. in_futures(4, ...) fetches four pages at once, in your program, waiting on the loop: one second for all four. Each page it gives goes on to in_workers(2, ...), which counts on two cores at once.
One at a time, it would take four seconds of fetching, then the counting. Here the fetching takes one, and the counting is shared.
Each half is written the way its stage needs: the fetch as an async sub in the program, as Ekorn::Pipeline::Futures has it, and the counting as a function in a module, as a worker needs it. What crosses between them is a page as a hash, plain data, which a worker can be sent.
This recipe is in this guide, not in Futures', because the workers are the half with rules to follow: the function in a module, plain data to send. Ekorn::Pipeline::Futures' guide links here.
What can go wrong
Don't swap the halves' places, putting the fetching in the workers with a blocking client, or the counting in Futures' block. The first works, but spends a worker, a whole perl, on each request in flight; the second computes in your one process, as the recipe before showed, gaining nothing.
Where next
Find duplicate files
The problem
A folder has many files, some of them copies of others under other names. You'd like to know which are the same.
You'll need
Ekorn::Pipeline::Workers:
cpanm Ekorn::Pipeline::Workers
The program
Save this module as lib/My/Checksum.pm:
package My::Checksum;
use v5.36;
use Digest::SHA;
# A file's path and its SHA-256 checksum, read in the worker.
sub of_file ($path) {
return {path => $path, sha256 => Digest::SHA->new(256)->addfile($path)->hexdigest};
}
1;
Then save this program as duplicates.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
use Ekorn::Pipeline::Tooling qw(drop_if);
# A folder of files to try it with, two of them the same. Use your own.
mkdir 'music';
my %holds = (
'music/waterloo.txt' => "Waterloo\n",
'music/parklife.txt' => "Parklife\n",
'music/copy-of-waterloo.txt' => "Waterloo\n",
);
for my $path (sort keys %holds) {
open my $out, '>:raw', $path or die "Can't write $path: $!\n";
print {$out} $holds{$path};
close $out or die "Can't write $path: $!\n";
}
my $pipeline = Ekorn::Pipeline->new(
drop_if { -z $_ },
in_workers(4, 'My::Checksum::of_file'),
);
# Group the paths by checksum, in the program.
my %paths_of;
for my $file ($pipeline->(glob 'music/*')) {
push @{ $paths_of{ $file->{sha256} } }, $file->{path};
}
for my $paths (grep { @$_ > 1 } values %paths_of) {
say 'the same: ', join ', ', sort @$paths;
}
# the same: music/copy-of-waterloo.txt, music/waterloo.txt
How it works
glob 'music/*' gives the folder's files. drop_if { -z $_ } drops empty ones before they reach a worker, as any two empty files are the same. Each worker reads its files and checksums them, the slow part, and sends back the path and checksum.
The grouping is in the program, in a hash of checksums to paths, as it needs every file's answer: a worker sees only its own. A checksum with more than one path is a set of copies.
What can go wrong
A file that can't be read, such as one without permission, makes its worker's function die, and the run stops, as chapter 6 shows. To skip such files and carry on, catch the failure in the function, as Keep going does.
Where next
Make a report from a database.
Make a report from a database
The problem
You'd like a CSV report of the tracks in your database, each with a score that takes real computing to work out, written as a file someone can open in a spreadsheet.
You'll need
Ekorn::Pipeline::Workers, DBIx::Squirrel, DBD::SQLite and Text::CSV:
cpanm Ekorn::Pipeline::Workers DBIx::Squirrel DBD::SQLite Text::CSV
The program
Save this module as lib/My/Score.pm:
package My::Score;
use v5.36;
use Digest::SHA qw(sha256);
# A track's score, from its title: hashing it a hundred thousand times
# stands in for real computing, such as analysing the audio.
sub of_track ($track) {
my $hash = $track->{title};
$hash = sha256($hash) for 1 .. 100_000;
return {%$track, score => unpack('N', $hash) % 100};
}
1;
Then save this program as report.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use DBIx::Squirrel;
use Ekorn::Pipeline::Workers qw(in_workers);
use Ekorn::Pipeline::Tooling qw(to_csv);
# A database to try it with. Use your own.
my $dbh = DBIx::Squirrel->connect('dbi:SQLite:dbname=:memory:', '', '', {RaiseError => 1});
$dbh->do('CREATE TABLE track (title TEXT, artist TEXT)');
$dbh->do('INSERT INTO track VALUES (?, ?)', undef, @$_)
for ['Parklife', 'Blur'], ['Waterloo', 'Abba'], ['White Room', 'Cream'];
my $written = $dbh->iterate(
'SELECT title, artist FROM track ORDER BY title',
{ekorn_slice => {}},
in_workers(3, 'My::Score::of_track'),
to_csv(file => 'report.csv', header => [qw(title artist score)]),
);
say "$written tracks in the report"; # 3 tracks in the report
open my $in, '<', 'report.csv' or die "Can't read report.csv: $!\n";
my($header, @rows) = <$in>;
print $header; # title,artist,score
my $scored = grep { m( ,\d+ \s* \z )x } @rows;
say scalar(@rows), ' rows, each with a score: ', ($scored == @rows ? 'yes' : 'no');
# 3 rows, each with a score: yes
How it works
The whole report is one pipeline. DBIx::Squirrel's iterate is the source, reading the tracks as hashes. in_workers computes each track's score on three cores, and gives back the track with its score added. to_csv is the sink, writing each, in the order of the query, as the workers keep the order. With a sink at its end, iterate runs the whole query at once, and gives what the sink gives: here, how many rows it wrote.
The database is read, and the file written, in the program, on one connection and one file. Only the computing is the workers'.
What can go wrong
A report that must be all or nothing shouldn't be written straight to its final name: if a score fails half way, a half-written report is left behind. Write to a temporary name, and rename it once the run succeeds.
Where next
Chapter 11 has the stages' limits, and every message they give.
11. Limits, and every message explained
Every limit of these stages comes from one fact: a worker is a new perl, which knows only what it loads and what it's sent. The earlier chapters show each where it bites:
The work is a named function in a module, never a block in your program: A worker is a new perl, not a copy of yours.
What crosses is a copy, made by Storable, so it must be plain data, never code, an open file or a connection: What a worker is given is a copy.
A worker sets itself up, connecting for itself, in
init: Run slow queries side by side, each worker connecting for itself.Every run starts its workers, which costs milliseconds, so the work must be worth it: chapter 7.
Work gains only from the cores, or connections, there are: Crunch numbers on several cores.
They're the same on Windows, Linux and macOS: only starting is slower on Windows.
Run workers inside a worker, knowing what it costs
The problem
Your function, in a worker, has work of its own that could be split again. You'd like to know whether a worker can use the stages itself.
You'll need
Ekorn::Pipeline::Workers:
cpanm Ekorn::Pipeline::Workers
The program
Save this module as lib/My/Albums.pm:
package My::Albums;
use v5.36;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
my %tracks = (Parklife => ['Girls & Boys', 'Parklife'], Arrival => ['Dancing Queen', 'Money, Money, Money']);
# Count one track's letters: the inner work.
sub letters_in ($title) {
return scalar(() = $title =~ m( [[:alpha:]] )xg);
}
# Count an album's letters, by counting each track's in workers of this
# worker's own.
sub letters_on ($album) {
my @counts = Ekorn::Pipeline->new(
in_workers(2, 'My::Albums::letters_in'),
)->(@{ $tracks{$album} });
my $total = 0;
$total += $_ for @counts;
return "$album: $total letters";
}
1;
Then save this program as nested.pl, beside lib:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Ekorn::Pipeline;
use Ekorn::Pipeline::Workers qw(in_workers);
my $pipeline = Ekorn::Pipeline->new(
in_workers(2, 'My::Albums::letters_on'),
);
say for $pipeline->(qw(Parklife Arrival));
# Parklife: 17 letters
# Arrival: 27 letters
How it works
A worker is a perl like any other, so it can run a pipeline with a workers' stage of its own. Each album's worker starts two workers for its tracks, as its value arrives, and ends them before it gives its answer. The program never sees the inner workers.
The inner workers find My::Albums as the outer ones did: each worker is given the program's places to look for modules, and passes them on.
What can go wrong
It works, but it multiplies. Two workers, each starting two, is six workers for two albums, and each inner run pays the start again, for every album. Splitting the work once, in your program, is nearly always better: here, sending every track to one set of workers, and adding up each album's letters after.
Where next
Every message the stages give.
Every message the stages give
The problem
A stage stopped your program with a message, and you'd like to know what it means, and what to do about it.
You'll need
Ekorn::Pipeline::Workers, as before.
The program
Save this module as lib/My/Slow.pm:
package My::Slow;
use v5.36;
sub look_up ($name) {
return "found $name";
}
# A second package in this file, which no worker could find.
package My::Slow::Inner;
sub look_up ($name) {
return "found $name";
}
1;
Then save this program as messages.pl, beside lib. Each mistake is one the stages refuse as they're made:
use v5.36;
use FindBin;
use lib "$FindBin::Bin/lib";
use Ekorn::Pipeline::Workers qw(in_workers once_per);
sub in_the_program ($name) { return $name }
for my $mistake (
sub { in_workers(0, 'My::Slow::look_up') },
sub { in_workers(2, 'My::Slow::look_up', windw => 4) },
sub { in_workers(2, 'My::Slow::look_up', window => 'four') },
sub { in_workers(2, 'My::Slow::look_up', window => 1) },
sub { in_workers(2, sub ($name) {$name}) },
sub { in_workers(2, \&in_the_program) },
sub { in_workers(2, 'look_up') },
sub { in_workers(2, 'main::in_the_program') },
sub { in_workers(2, 'My::Slow::Inner::look_up') },
sub { in_workers(2, 'My::Slow::look_it_up') },
sub { in_workers(2, 'My::Quick::look_up') },
sub { in_workers(2, 'My::Slow::look_up', init_args => 'dbi:SQLite:dbname=music.db') },
sub { in_workers(2, 'My::Slow::look_up', init_args => ['dbi:SQLite:dbname=music.db']) },
sub { once_per('artist', 2, 'My::Slow::look_up') },
sub { once_per(sub ($track) { $track->{artist} }, 2, 'My::Slow::look_up', join => 'merge') },
sub { once_per(sub ($track) { $track->{artist} }, 2, 'My::Slow::look_up', hold => 'lots') },
) {
eval { $mistake->() };
print $@ =~ s( :\ a\ worker\ is\ a\ new\ perl.* )( ...\n)xsr =~ s( \ in\ \@INC\ .* )( ...\n)xsr;
}
# Expected a number of workers of 1 or more at ... line ...
# Expected no option windw at ... line ...
# Expected window to be a whole number at ... line ...
# Expected a window at least the number of workers at ... line ...
# Expected the function to be a named sub in a module, not an anonymous one ...
# Expected the function to be a sub in a module, not the program's main::in_the_program ...
# Expected the function to be given by name, as 'Module::function', or as a code reference to one ...
# Expected the function to be a sub in a module, not the program's main::in_the_program ...
# Expected the function to be in a module of its own name, My::Slow::Inner, which a worker can load at ... line ...
# Expected the function to exist, but there's no My::Slow::look_it_up at ... line ...
# Expected the function's module, My::Quick, to load: Can't locate My/Quick.pm ...
# Expected init_args to be an array reference at ... line ...
# Expected init with init_args at ... line ...
# Expected a code reference for the key at ... line ...
# Expected a code reference to join at ... line ...
# Expected hold to be a whole number at ... line ...
How it works
Each of these is refused as the stage is made, before any worker starts, so the message names the line that made it. The two substitutions shorten the longest messages for the guide: the first cuts the reason after "a worker is a new perl", the second the list of places perl looked for a module.
Every message, what it means, and what to do:
- Expected a number of workers of 1 or more
-
Give a whole number, 1 or more: Choose how many workers.
- Expected no option %s
-
The stage doesn't take an option of that name: check its spelling.
orderedisonce_per's alone;in_workers_as_readyis the same forin_workers. - Expected window to be a whole number
-
Give
windowa number of values, such as8. - Expected a window at least the number of workers
-
windowcan't be less than the number of workers, or some would never be sent a value. - Expected %s to be a named sub in a module, not an anonymous one: a worker is a new perl, which it can't reach
-
Move the code into a function in a module: A worker is a new perl, not a copy of yours.
- Expected %s to be a sub in a module, not the program's %s: a worker is a new perl, which loads modules, not the program
-
Move the function from your program into a module: Name the function with a code reference.
- Expected %s to be given by name, as 'Module::function', or as a code reference to one: a worker is a new perl, which a closure in this one can't reach
-
Name the function with its module,
'My::Slow::look_up', not alone. - Expected %s to be in a module of its own name, %s, which a worker can load
-
The function is in a second package of another module's file, where no worker would look for it: give it a module file of its own name.
- Expected %s to exist, but there's no %s
-
The module loaded, but has no function of that name: check its spelling.
- Expected %s's module, %s, to load: %s
-
Perl couldn't load the module, for the reason given: Run three slow jobs at once shows the usual one, a missing
use lib. - Expected init_args to be an array reference
-
Put
init's arguments in[...]: Giveinitwhat it needs. - Expected init with init_args
-
init_argsare given toinit, which you left out: add it, or drop them. - Expected a code reference for the key
-
once_per's first argument is code giving each value's key, run in your program. - Expected a code reference to join
-
joinis code, run in your program, given the value and its key's answer. - Expected hold to be a whole number
-
Give
holda number of values, such as100, or 0. - Expected a key for each value, not undef
-
A value gave no key: Look each artist up once.
- %s can't send %s #%s to a worker: %s
-
The value can't be copied: What a worker is given is a copy.
- %s can't send back the results of %s #%s: %s
-
What the function returned can't be copied: Give several results, or none.
- %s can't send its init_args to a worker: %s
-
init_argsholds what can't be copied, such as a handle: Run slow queries side by side. - %s couldn't set up a worker: %s
-
initdied, with its message: Set each worker up once. - %s lost worker %s, which exited, status %s, with %s #%s
-
A worker ended without answering: Know when a worker dies.
- %s waited 30s for its workers to start
-
The workers didn't start, or didn't connect back: a computer far too busy, or something stopping new processes.
- %s can't listen for its workers: %s
-
It couldn't open a socket on 127.0.0.1 for the workers to connect to, as security software might forbid.
- %s couldn't start a worker: %s
-
The system wouldn't start another process, as when too many are running.
- %s lost worker %s: %s
-
A worker's connection broke while a value was being sent.
The last four are the system failing, not your program, so no recipe can make them; each says what the system said.
What can go wrong
The first sixteen come as the stage is made, so they name the line that made it. The rest come from a run, so they follow "Pipeline stage #1 failed at ...", which names the line that ran the pipeline. Each starts with the name of the stage that gave it, in_workers, in_workers_as_ready or once_per, and once_per's speak of keys, not values, as keys are what it sends. The other %ss are filled in with the value's number, counted from 1, the worker's process number, or what Storable or the system said.
Messages from your own function, or a library it calls, are passed on as they were. The module's own documentation, Ekorn::Pipeline::Workers, has these messages under DIAGNOSTICS.
Where next
Chapter 12 answers questions you may have.
12. Questions you may have
How fast is it?
Starting the workers costs about 13 milliseconds each on a Mac, and a quarter to half a second for four on Windows, once a run. Then each value costs about 32 microseconds on a Mac, on top of its work, to cross to a worker and back. So work of milliseconds a value, over many values, gains nearly all the workers can give; chapter 7 measures it on yours.
How much does it hold in memory?
Each worker is a perl, with what its module loads: a few megabytes or more each. In your program, in_workers holds at most its window of values and their results, by default twice as many as it has workers, and takes a new value from its source only when it has room. once_per keeps every key's answer for the run, and holds up to 1,000 values waiting for answers, as hold sets.
Does it use fork, threads or MCE?
No threads and no MCE. Each worker is a new perl: on Linux and macOS, fork then, at once, exec of a new perl, so nothing of your program is kept; on Windows, a new process. Each talks to your program over a connection of its own on 127.0.0.1, your own computer, and values cross by Storable, which comes with Perl.
That's why it behaves the same everywhere, and why the rules are what they are: A worker is a new perl, not a copy of yours.
Should I use this, Ekorn::Pipeline::Futures, or neither?
Use Ekorn::Pipeline::Workers when the work blocks, as the DBI does, or a module with only a blocking interface, or keeps the CPU busy, as counting or compressing does.
Use Ekorn::Pipeline::Futures when the work waits on I/O a library can wait on asynchronously, giving Futures or promises: web requests through Mojo::UserAgent, anything on IO::Async.
Use neither, an ordinary stage, when each value's work takes microseconds.
One problem, three ways shows all three, timed, and Futures feeding Workers uses both in one pipeline.
Does it work on Windows?
Yes. Every recipe in this guide runs on Windows, with Strawberry Perl, on every change, as well as on Linux and macOS. The rules are the same on all three; only starting the workers is slower on Windows.
Does it need anything else installed?
No. Ekorn::Pipeline::Workers needs only Ekorn::Pipeline, and modules that come with Perl. What your functions use, such as DBIx::Squirrel, is yours to install, as each recipe's "You'll need" says.
Can my function use modules from CPAN?
Yes. A worker loads your module, and your module loads what it likes. Workers look for modules where your program does, so anything your program can load, a worker can too.
Is it safe with my database handles?
Yes. No worker gets a copy of your program's handle, so none can close it, or use it at the same time as your program. Each worker connects for itself, in init, as chapter 3 shows, and your program's handle works as before, during the run and after.
Can workers stay up between runs?
No. Each run starts its own, at its first value, and ends them with it, so nothing one run left in a worker can surprise the next. Give a pipeline all its values in one run, or push them through a feed, as chapter 7 and chapter 9 show.
Can I use it in a web app?
In the app's scripts and jobs, yes. In a request's handler, think twice: a run starts its workers, and holds that request until every value is done, so each request would pay for starting workers. Hand such work to a job that runs on its own, and let the handler answer at once.
Who can talk to the workers?
Each worker connects to your program on 127.0.0.1, so only programs on the same computer can reach it, and gives a token the program made for it, so no other connection is taken for a worker. The token goes to the worker in its environment, which only your own user, and the computer's administrator, can read, never on its command line, which every user can. So other users of the computer can't pose as a worker, and be sent what your workers are, such as init_args.
Where can I read more?
The module's own documentation, Ekorn::Pipeline::Workers, has the rules for each stage and option, what happens on a failure or a stop, and every message.
Ekorn::Pipeline's guide, Ekorn::Pipeline::Manual::HowTo, covers everything around the stages: sources, stages, sinks, and functions that take stages.
Ekorn::Pipeline::Futures' guide, Ekorn::Pipeline::Futures::Manual::HowTo, covers the other kind of waiting.
The appendix, next, matches each of the stages' promises to the recipes that show it.
Appendix: what writing this guide proved, and found
Every program in this guide is a test. Each runs as it stands, alone, with the modules it saves beside it, on Linux, macOS and Windows, on every change to the module, and must print exactly what it says it prints. So, taken together, the recipes check the stages' promises from a reader's side, with real databases, files and Ekorn's own parts. Writing them also found things that needed changing, and traps that a reader can still fall into.
What the recipes prove
- Each worker is a process of its own, never the program
- A worker is a new perl, with nothing of the program's but what it's sent
- What crosses is a copy, and what can't be copied is refused, naming the value
-
What a worker is given is a copy, Give several results, or none
- Up to the number given work at once, and no more
in_workersgives results in the order the values camein_workers_as_readygives each result as soon as it's backinitruns once in each worker,doneas it leaves, and a failedinitfails the run- A worker connects to a database for itself, in
init, and the program writes on its own once_perlooks each key up once, and sends only the key- Each result knows the value it came from
- A failure takes its turn, after the results before it
- An error object is passed on as it was
- A stop takes its turn, with its values
- A stop after the stage ends the workers
- A worker that dies is an error naming its value
- A failure met in the flush loses the results taken with it
- Workers start at a run's first value, so an empty run starts none, and end with the run
-
See that an empty run starts nothing, Run once over many values, not once a value
- Work for the CPU runs on several cores
- The stages are stages like any other, beside all of Ekorn's parts, and Futures'
-
chapters 5, 9 and 10: sources, stages, sinks, iterators, named pipelines, pipelines as stages, feeds, and Futures feeding Workers
- Each mistake is refused with a message saying what to do
What writing them found
Some of what the recipes found changed the module before it was ever released:
The stages are exported by default, as Ekorn::Pipeline::Futures' are. This guide still names what each program uses.
An error object crosses as it was. A worker used to send every error as its message, so an exception class's object reached the program as
HASH(0x...), and couldn't be caught by its class.The messages say "the function", not "block", a word this guide doesn't use for it, and count values from 1, as Ekorn counts stages and results.
The messages leave out Storable's own file and line, which told you nothing you could act on.
A module that won't load says why. A program that left out its
use libwas told there was no such function, when the trouble was that perl couldn't find the module.
Others are traps that remain, as they come from Perl, or from what a worker is. Each has a recipe:
**Perl's own
sleeptakes whole seconds,** sosleep 0.2doesn't wait at all.use Time::HiRes qw(sleep)gives one that takes fractions, as the recipes that nap for less than a second do.A block of code can't be the work, as no worker can reach your program. Put it in a function in a module, as A worker is a new perl, not a copy of yours shows.
A setting changed in your program isn't in a worker, which loads your module afresh. Send it with
init_args, as Giveinitwhat it needs does.A DBIx::Squirrel row object has no methods in a worker, as its class is made by the query, in your program. Send rows as hashes, as Send rows as hashes, not objects does.
A failure near the end can take results with it. Catch failures in the function, as Keep going: turn each failure into a result does.
What a worker prints can come out late, mixed with your program's. Give back what you'd print, and print it in your program, as Know when a worker dies says.
Work that takes microseconds is slower in workers. Batch it, as Batch small work does, or use an ordinary stage.
The whole account, with each decision taken and why, is in Ekorn-Pipeline's change record for these stages, 2026-0065.
SEE ALSO
Ekorn::Pipeline::Workers, Ekorn::Pipeline, Ekorn::Pipeline::Manual::HowTo, Ekorn::Pipeline::Futures::Manual::HowTo
AUTHOR
Iain Campbell <cpanic@cpan.org>
LICENSE
Copyright (c) 2026 by Iain Campbell.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.