summaryrefslogtreecommitdiff
path: root/lib/MCE/Examples.pod
blob: ccd798fa862de6d48853e8267d0047c75bacb7d9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
=head1 NAME

MCE::Examples - Various examples and demonstrations

=head1 VERSION

This document describes MCE::Examples version 1.888

=head1 INCLUDED WITH THE DISTRIBUTION

A wrapper script for parallelizing the grep binary. Hence, processing is done
by the binary, not Perl. This wrapper resides under the bin directory.

  mce_grep
      A wrapper script with support for the following C binaries.
      agrep, grep, egrep, fgrep, and tre-agrep

      Chunking may be applied either at the [file] level, for large
      file(s), or at the [list] level when parsing many files
      recursively.

      The gain in performance is noticeable for expensive patterns,
      especially with agrep and tre-agrep.

=head1 MCE EXAMPLES ON GITHUB

The examples directory, beginning with 1.700, is maintained separately at a
GitHub repository L<https://github.com/marioroy/mce-examples> and no longer
included with the Perl MCE distribution.

=head1 PROCESSING INPUT DATA

The next section describes ways to process input data in MCE.

=head2 CHUNK_SIZE => 1 (in essence, disabling chunking)

Imagine a long running process and wanting to parallelize an array against a
pool of workers. The sequence option may be used if simply wanting to loop
through a sequence of numbers instead.

Below, a callback function is used for displaying results. The logic shows
how one can output results immediately while still preserving output order
as if processing serially. The %tmp hash is a temporary cache for
out-of-order results.

 use MCE;

 ## Return an iterator for preserving output order.

 sub preserve_order {
    my (%result_n, %result_d); my $order_id = 1;

    return sub {
       my ($chunk_id, $n, $data) = @_;

       $result_n{ $chunk_id } = $n;
       $result_d{ $chunk_id } = $data;

       while (1) {
          last unless exists $result_d{$order_id};

          printf "n: %5d sqrt(n): %7.3f\n",
             $result_n{$order_id}, $result_d{$order_id};

          delete $result_n{$order_id};
          delete $result_d{$order_id};

          $order_id++;
       }

       return;
    };
 }

 ## Use $chunk_ref->[0] or $_ to retrieve the element.
 my @input_data = (0 .. 18000 - 1);

 my $mce = MCE->new(
    gather => preserve_order, input_data => \@input_data,
    chunk_size => 1, max_workers => 3,

    user_func => sub {
       my ($mce, $chunk_ref, $chunk_id) = @_;
       MCE->gather($chunk_id, $_, sqrt($_));
    }
 );

 $mce->run;

This does the same thing using the foreach "sugar" method. 

 use MCE;

 sub preserve_order {
    ...
 }

 my $mce = MCE->new(
    chunk_size => 1, max_workers => 3,
    gather => preserve_order
 );

 ## Use $chunk_ref->[0] or $_ to retrieve the element.
 my @input_data = (0 .. 18000 - 1);

 $mce->foreach( \@input_data, sub {
    my ($mce, $chunk_ref, $chunk_id) = @_;
    MCE->gather($chunk_id, $_, sqrt($_));
 });

The 2 examples described above were done using the Core API. MCE 1.5 comes
with several models. The L<MCE::Loop> model is used below.

 use MCE::Loop;

 sub preserve_order {
    ...
 }

 MCE::Loop->init(
    chunk_size => 1, max_workers => 3,
    gather => preserve_order
 );

 ## Use $chunk_ref->[0] or $_ to retrieve the element.
 my @input_data = (0 .. 18000 - 1);

 mce_loop {
    my ($mce, $chunk_ref, $chunk_id) = @_;
    MCE->gather($chunk_id, $_, sqrt($_));

 } @input_data;

 MCE::Loop->finish;

=head2 CHUNKING INPUT DATA

Chunking has the effect of reducing IPC overhead by many folds. A chunk
containing $chunk_size items is sent to the next available worker.

 use MCE;

 ## Return an iterator for preserving output order.

 sub preserve_order {
    my (%result_n, %result_d, $size); my $order_id = 1;

    return sub {
       my ($chunk_id, $n_ref, $data_ref) = @_;

       $result_n{ $chunk_id } = $n_ref;
       $result_d{ $chunk_id } = $data_ref;

       while (1) {
          last unless exists $result_d{$order_id};
          $size = @{ $result_d{$order_id} };

          for (0 .. $size - 1) {
             printf "n: %5d sqrt(n): %7.3f\n",
                $result_n{$order_id}->[$_], $result_d{$order_id}->[$_];
          }

          delete $result_n{$order_id};
          delete $result_d{$order_id};

          $order_id++;
       }

       return;
    };
 }

 ## Chunking requires one to loop inside the code block.
 my @input_data = (0 .. 18000 - 1);

 my $mce = MCE->new(
    gather => preserve_order, input_data => \@input_data,
    chunk_size => 500, max_workers => 3,

    user_func => sub {
       my ($mce, $chunk_ref, $chunk_id) = @_;
       my (@n, @result);

       foreach ( @{ $chunk_ref } ) {
          push @n, $_;
          push @result, sqrt($_);
       }

       MCE->gather($chunk_id, \@n, \@result);
    }
 );

 $mce->run;

This does the same thing using the forchunk "sugar" method. 

 use MCE;

 sub preserve_order {
    ...
 }

 my $mce = MCE->new(
    chunk_size => 500, max_workers => 3,
    gather => preserve_order
 );

 ## Chunking requires one to loop inside the code block.
 my @input_data = (0 .. 18000 - 1);

 $mce->forchunk( \@input_data, sub {
    my ($mce, $chunk_ref, $chunk_id) = @_;
    my (@n, @result);

    foreach ( @{ $chunk_ref } ) {
       push @n, $_;
       push @result, sqrt($_);
    }

    MCE->gather($chunk_id, \@n, \@result);
 });

Finally, chunking with the L<MCE::Loop> model.

 use MCE::Loop;

 sub preserve_order {
    ...
 }

 MCE::Loop->init(
    chunk_size => 500, max_workers => 3,
    gather => preserve_order
 );

 ## Chunking requires one to loop inside the code block.
 my @input_data = (0 .. 18000 - 1);

 mce_loop {
    my ($mce, $chunk_ref, $chunk_id) = @_;
    my (@n, @result);

    foreach ( @{ $chunk_ref } ) {
       push @n, $_;
       push @result, sqrt($_);
    }

    MCE->gather($chunk_id, \@n, \@result);

 } @input_data;

 MCE::Loop->finish;

=head1 DEMO APPLYING SEQUENCES WITH USER_TASKS

The following is an extract from the seq_demo.pl example included with MCE. 
Think of having several MCEs running in parallel. The sequence and chunk_size
options may be specified uniquely per each task.

The input scalar $_ (not shown below) contains the same value as $seq_n in
user_func.

 use MCE;
 use Time::HiRes 'sleep';

 ## Run with seq_demo.pl | sort

 sub user_func {
    my ($mce, $seq_n, $chunk_id) = @_;

    my $wid      = MCE->wid;
    my $task_id  = MCE->task_id;
    my $task_wid = MCE->task_wid;

    if (ref $seq_n eq 'ARRAY') {
       ## seq_n or $_ is an array reference when chunk_size > 1
       foreach (@{ $seq_n }) {
          MCE->printf(
             "task_id %d: seq_n %s: chunk_id %d: wid %d: task_wid %d\n",
             $task_id,    $_,       $chunk_id,   $wid,   $task_wid
          );
       }
    }
    else {
       MCE->printf(
          "task_id %d: seq_n %s: chunk_id %d: wid %d: task_wid %d\n",
          $task_id,    $seq_n,   $chunk_id,   $wid,   $task_wid
       );
    }

    sleep 0.003;

    return;
 }

 ## Each task can be configured uniquely.

 my $mce = MCE->new(
    user_tasks => [{
       max_workers => 2,
       chunk_size  => 1,
       sequence    => { begin => 11, end => 19, step => 1 },
       user_func   => \&user_func
    },{
       max_workers => 2,
       chunk_size  => 5,
       sequence    => { begin => 21, end => 29, step => 1 },
       user_func   => \&user_func
    },{
       max_workers => 2,
       chunk_size  => 3,
       sequence    => { begin => 31, end => 39, step => 1 },
       user_func   => \&user_func
    }]
 );

 $mce->run;

 -- Output

 task_id 0: seq_n 11: chunk_id 1: wid 2: task_wid 2
 task_id 0: seq_n 12: chunk_id 2: wid 1: task_wid 1
 task_id 0: seq_n 13: chunk_id 3: wid 2: task_wid 2
 task_id 0: seq_n 14: chunk_id 4: wid 1: task_wid 1
 task_id 0: seq_n 15: chunk_id 5: wid 2: task_wid 2
 task_id 0: seq_n 16: chunk_id 6: wid 1: task_wid 1
 task_id 0: seq_n 17: chunk_id 7: wid 2: task_wid 2
 task_id 0: seq_n 18: chunk_id 8: wid 1: task_wid 1
 task_id 0: seq_n 19: chunk_id 9: wid 2: task_wid 2
 task_id 1: seq_n 21: chunk_id 1: wid 3: task_wid 1
 task_id 1: seq_n 22: chunk_id 1: wid 3: task_wid 1
 task_id 1: seq_n 23: chunk_id 1: wid 3: task_wid 1
 task_id 1: seq_n 24: chunk_id 1: wid 3: task_wid 1
 task_id 1: seq_n 25: chunk_id 1: wid 3: task_wid 1
 task_id 1: seq_n 26: chunk_id 2: wid 4: task_wid 2
 task_id 1: seq_n 27: chunk_id 2: wid 4: task_wid 2
 task_id 1: seq_n 28: chunk_id 2: wid 4: task_wid 2
 task_id 1: seq_n 29: chunk_id 2: wid 4: task_wid 2
 task_id 2: seq_n 31: chunk_id 1: wid 5: task_wid 1
 task_id 2: seq_n 32: chunk_id 1: wid 5: task_wid 1
 task_id 2: seq_n 33: chunk_id 1: wid 5: task_wid 1
 task_id 2: seq_n 34: chunk_id 2: wid 6: task_wid 2
 task_id 2: seq_n 35: chunk_id 2: wid 6: task_wid 2
 task_id 2: seq_n 36: chunk_id 2: wid 6: task_wid 2
 task_id 2: seq_n 37: chunk_id 3: wid 5: task_wid 1
 task_id 2: seq_n 38: chunk_id 3: wid 5: task_wid 1
 task_id 2: seq_n 39: chunk_id 3: wid 5: task_wid 1

=head1 GLOBALLY SCOPED VARIABLES AND MCE MODELS

It is possible that Perl may create a new code ref on subsequent runs causing
MCE models to re-spawn. One solution to this is to declare global variables,
referenced by workers, with "our" instead of "my".

Let's take a look. The $i variable is declared with my and being reference in
both user_begin and mce_loop blocks. This will cause Perl to create a new code
ref for mce_loop on subsequent runs.

 use MCE::Loop;

 my $i = 0;   ## <-- this is the reason, try our instead

 MCE::Loop->init(
    user_begin => sub {
       print "process_id: $$\n" if MCE->wid == 1;
       $i++;
    },
    chunk_size => 1, max_workers => 'auto',
 );

 for (1..2) {
    ## Perl creates another code block ref causing workers
    ## to re-spawn on subsequent runs.
    print "\n"; mce_loop { print "$i: $_\n" } 1..4;
 }

 MCE::Loop->finish;

 -- Output

 process_id: 51380
 1: 1
 1: 2
 1: 3
 1: 4

 process_id: 51388
 1: 1
 1: 2
 1: 3
 1: 4

By making the one line change, we see that workers persist for the duration of
the script.

 use MCE::Loop;

 our $i = 0;  ## <-- changed my to our

 MCE::Loop->init(
    user_begin => sub {
       print "process_id: $$\n" if MCE->wid == 1;
       $i++;
    },
    chunk_size => 1, max_workers => 'auto',
 );

 for (1..2) {
    ## Workers persist between runs. No re-spawning.
    print "\n"; mce_loop { print "$i: $_\n" } 1..4;
 }

 -- Output

 process_id: 51457
 1: 1
 1: 2
 1: 4
 1: 3

 process_id: 51457
 2: 1
 2: 2
 2: 3
 2: 4

One may alternatively specify a code reference to existing routines for
user_begin and mce_loop. Take notice of the comma after \&_func though.

 use MCE::Loop;

 my $i = 0;  ## my (ok)

 sub _begin {
    print "process_id: $$\n" if MCE->wid == 1;
    $i++;
 }
 sub _func {
    print "$i: $_\n";
 }

 MCE::Loop->init(
    user_begin => \&_begin,
    chunk_size => 1, max_workers => 'auto',
 );

 for (1..2) {
    print "\n"; mce_loop \&_func, 1..4;
 }

 MCE::Loop->finish;

 -- Output

 process_id: 51626
 1: 1
 1: 2
 1: 3
 1: 4

 process_id: 51626
 2: 1
 2: 2
 2: 3
 2: 4

=head1 MANDELBROT DEMONSTRATION

For the next demonstration, L<MCE::Relay> allows a section of code to run
serially and orderly between workers. Relay capabilities is enabled with
the C<init_relay> option, which loads MCE::Relay.

 # perl mandelbrot.pl 16000 > image.pbm
 # outputs a pbm binary to STDOUT

 # The Computer Language Benchmarks Game
 # https://benchmarksgame-team.pages.debian.net/benchmarksgame/
 #
 # Started with:
 # C#  : Adapted by Antti Lankila from Isaac Gouy's implementation
 # Perl: Contributed by Mykola Zubach
 #
 # MCE::Loop version by Mario Roy
 # requires MCE 1.807+

 use strict;
 use warnings;

 use MCE::Loop;

 use constant MAXITER => 50;
 use constant LIMIT   => 4.0;
 use constant XMIN    => -1.5;
 use constant YMIN    => -1.0;

 my ( $w, $h, $m, $invN );

 sub draw_lines {
    my ( $y1, $y2 ) = @_;
    my @result;

    # Workers run simultaneously, in parallel.

    for my $y ( $y1 .. $y2 ) {
       my ( $bits, $xcounter, @line ) = ( 0, 0 );
       my $Ci = $y * $invN + YMIN;

       for my $x ( 0 .. $w - 1 ) {
          my ( $Zr, $Zi, $Tr, $Ti ) = ( 0, 0, 0, 0 );
          my $Cr = $x * $invN + XMIN;

          $bits = $bits << 1;

          for ( 1 .. MAXITER ) {
             $Zi = $Zi * 2 * $Zr + $Ci;
             $Zr = $Tr - $Ti + $Cr;
             $Ti = $Zi * $Zi, $Tr = $Zr * $Zr;

             $bits |= 1, last if ( $Tr + $Ti > LIMIT );
          }

          if ( ++$xcounter == 8 ) {
             push @line, $bits ^ 0xff;
             $bits = $xcounter = 0;
          }
       }

       if ( $xcounter ) {
          push @line, ( $bits << ( 8 - $xcounter ) ) ^ 0xff;
       }

       push @result, pack 'C*', @line;
    }

    # Statements between lock & unlock are processed serially & orderly.

    MCE->relay_lock;

    print @result;          # Workers display upper-half only.
    MCE->gather( @result ); # Gather lines for the manager-process.

    MCE->relay_unlock;
 }

 ## MAIN()

 # Important, must flush output immediately.

 $| = 1; binmode STDOUT;

 $w = $h = shift || 200;
 $m = int( $h / 2 );
 $invN = 2 / $w;

 print "P4\n$w $h\n"; # PBM image header.

 # Workers display upper-half only. Also, lines are gathered to be
 # displayed later by the manager-process after running.

 MCE::Loop->init(
    init_relay  => 0, # Enables MCE::Relay capabilities if defined.
    max_workers => 4,
    bounds_only => 1,
 );

 my @upper = mce_loop_s { draw_lines( $_[1][0], $_[1][1] ) } 0, $m;

 MCE::Loop->finish;

 # Remove first and last lines from the upper half.
 # Then, output bottom half.

 shift @upper, pop @upper;
 print reverse @upper;

=head1 MONTE CARLO SIMULATION

There is an article on the web (search for comp.lang.perl.misc MCE) suggesting
that MCE::Examples does not cover a simple simulation scenario. This section
demonstrates just that.

The serial code is based off the one by "gamo". A sleep is added to imitate
extra CPU time. The while loop is wrapped within a for loop to run 10 times.
The random number generator is seeded as well.

 use Time::HiRes qw/sleep time/;

 srand 5906;

 my ($var, $foo, $bar) = (1, 2, 3);
 my ($r, $a, $b);

 my $start = time;

 for (1..10) {
    while (1) {
       $r = rand;

       $a = $r * ($var + $foo + $bar);
       $b = sqrt($var + $foo + $bar);

       last if ($a < $b + 0.001 && $a > $b - 0.001);
       sleep 0.002;
    }

    print "$r -> $a\n";
 }

 my $end = time;

 printf {*STDERR} "\n## compute time: %0.03f secs\n\n", $end - $start;

 -- Output

 0.408246276657106 -> 2.44947765994264
 0.408099657137821 -> 2.44859794282693
 0.408285842931324 -> 2.44971505758794
 0.408342292008765 -> 2.45005375205259
 0.408333076522673 -> 2.44999845913604
 0.408344266898869 -> 2.45006560139321
 0.408084104120526 -> 2.44850462472316
 0.408197400014714 -> 2.44918440008828
 0.408344783704855 -> 2.45006870222913
 0.408248062985479 -> 2.44948837791287

 ## compute time: 93.049 secs

Next, we'd do the same with MCE. The demonstration requires at least MCE 1.509
to run properly. Folks on prior releases (1.505 - 1.508) will not see output
for the 2nd run and beyond.

 use Time::HiRes qw/sleep time/;
 use MCE::Loop;

 srand 5906;

 ## Configure MCE. Move common variables inside the user_begin
 ## block when not needed by the manager process.

 MCE::Loop->init(
    user_begin => sub {
       use vars qw($var $foo $bar);
       our ($var, $foo, $bar) = (1, 2, 3);
    },
    chunk_size => 1, max_workers => 'auto',
    input_data => \&_input, gather => \&_gather
 );

 ## Callback functions.

 my ($done, $r, $a);

 sub _input {
    return if $done;
    return rand;
 }

 sub _gather {
    my ($_r, $_a, $_b) = @_;
    return if $done;

    if ($_a < $_b + 0.001 && $_a > $_b - 0.001) {
       ($done, $r, $a) = (1, $_r, $_a);
    }
    return;
 }

 ## Compute in parallel.

 my $start = time;

 for (1..10) {
    $done = 0;      ## Reset $done before running

    mce_loop {
     # my ($mce, $chunk_ref, $chunk_id) = @_;
     # my $r = $chunk_ref->[0];

       my $r = $_;  ## Valid due to chunk_size => 1

       my $a = $r * ($var + $foo + $bar);
       my $b = sqrt($var + $foo + $bar);

       MCE->gather($r, $a, $b);
       sleep 0.002;
    };

    print "$r -> $a\n";
 }

 printf "\n## compute time: %0.03f secs\n\n", time - $start;

 -- Output

 0.408246276657106 -> 2.44947765994264
 0.408099657137821 -> 2.44859794282693
 0.408285842931324 -> 2.44971505758794
 0.408342292008765 -> 2.45005375205259
 0.408333076522673 -> 2.44999845913604
 0.408344266898869 -> 2.45006560139321
 0.408084104120526 -> 2.44850462472316
 0.408197400014714 -> 2.44918440008828
 0.408344783704855 -> 2.45006870222913
 0.408248062985479 -> 2.44948837791287

 ## compute time: 12.990 secs

Well, there you have it. MCE is able to complete the same simulation many
times faster.

=head1 MANY WORKERS RUNNING IN PARALLEL

There are occasions when one wants several workers to run in parallel without
having to specify input_data or sequence. These two options are optional in
MCE. The "do" and "sendto" methods, for sending data to the manager process,
are demonstrated below. Both process serially by the manager process on a
first come, first serve basis.

 use MCE::Flow max_workers => 4;

 sub report_stats {
    my ($wid, $msg, $h_ref) = @_;
    print "Worker $wid says $msg: ", $h_ref->{"counter"}, "\n";
 }

 mce_flow sub {
    my ($mce) = @_;
    my $wid = MCE->wid;

    if ($wid == 1) {
       my %h = ("counter" => 0);
       while (1) {
          $h{"counter"} += 1;
          MCE->do("report_stats", $wid, "Hey there", \%h);
          last if ($h{"counter"} == 4);
          sleep 2;
       }
    }
    else {
       my %h = ("counter" => 0);
       while (1) {
          $h{"counter"} += 1;
          MCE->do("report_stats", $wid, "Welcome..", \%h);
          last if ($h{"counter"} == 2);
          sleep 4;
       }
    }

    MCE->print(\*STDERR, "Worker $wid is exiting\n");
 };

 -- Output

 Note how worker 2 comes first in the 2nd run below.

 $ ./demo.pl
 Worker 1 says Hey there: 1
 Worker 2 says Welcome..: 1
 Worker 3 says Welcome..: 1
 Worker 4 says Welcome..: 1
 Worker 1 says Hey there: 2
 Worker 2 says Welcome..: 2
 Worker 3 says Welcome..: 2
 Worker 1 says Hey there: 3
 Worker 2 is exiting
 Worker 3 is exiting
 Worker 4 says Welcome..: 2
 Worker 4 is exiting
 Worker 1 says Hey there: 4
 Worker 1 is exiting

 $ ./demo.pl
 Worker 2 says Welcome..: 1
 Worker 1 says Hey there: 1
 Worker 4 says Welcome..: 1
 Worker 3 says Welcome..: 1
 Worker 1 says Hey there: 2
 Worker 2 says Welcome..: 2
 Worker 4 says Welcome..: 2
 Worker 3 says Welcome..: 2
 Worker 2 is exiting
 Worker 4 is exiting
 Worker 1 says Hey there: 3
 Worker 3 is exiting
 Worker 1 says Hey there: 4
 Worker 1 is exiting

=head1 TESTING AND CAPTURING OUTPUT

Capturing C<STDERR> and C<STDOUT> is possible with L<App::Cmd::Tester>.
MCE v1.708 or later is required to run the demonstration.

 use App::Cmd::Tester;
 use MCE;

 my $mce = MCE->new(
    max_workers => 4,

    user_func => sub {
       my $wid = MCE->wid;

       # MCE->sendto('stderr', "$wid: sendto err\n");
       # MCE->sendto(\*STDERR, "$wid: sendto err\n");
         MCE->print(\*STDERR, "$wid: print err\n");

       # MCE->sendto('stdout', "$wid: sendto out\n");
       # MCE->sendto(\*STDOUT, "$wid: sendto out\n");
       # MCE->print(\*STDOUT, "$wid: print out\n");
         MCE->print("$wid: print out\n");
    }
 );

 my $result = test_app(
    $mce => []
 );

 print "# stderr\n";
 print $result->stderr;
 print "\n";

 print "# stdout\n";
 print $result->stdout;
 print "\n";

 print "# output\n";
 print $result->output;
 print "\n";

 print "# exit code\n";
 print $result->exit_code;
 print "\n\n";

 -- Output

 # stderr
 3: print err
 4: print err
 1: print err
 2: print err

 # stdout
 3: print out
 4: print out
 1: print out
 2: print out

 # output
 3: print err
 3: print out
 4: print err
 1: print err
 4: print out
 1: print out
 2: print err
 2: print out

 # exit code
 0

The next demonstration captures a sequence of numbers orderly. The slot name
for C<IO::TieCombine> must be C<stdout> or C<stderr> for MCE->print to work.

 use MCE::Flow;
 use MCE::Candy;
 use IO::TieCombine;

 my $hub = IO::TieCombine->new;

 {
    tie local *STDOUT, $hub, 'stdout';

    MCE::Flow->init(
       max_workers => 4,
       chunk_size  => 500,
       bounds_only => 1,
       gather      => MCE::Candy::out_iter_fh(\*STDOUT),
    );

    mce_flow_s sub {
       my ($mce, $seq, $chunk_id) = @_;
       my $output = '';

       for my $n ( $seq->[0] .. $seq->[1] ) {
          $output .= "$n\n";
       }

       # do this if output order is not required
       # $mce->print(\*STDOUT, $output);

       # or this if preserving output order is desired
         $mce->gather($chunk_id, $output);

    }, 1, 100000;

    MCE::Flow->finish;
 }

 my $content = $hub->slot_contents('stdout');
 my $answer  = join("", map { "$_\n" } 1..100000);

 if ($content eq $answer) {
    print "ordered: yes\n";
 } else {
    print "ordered: no\n";
 }

 -- Output

 ordered: yes

=head1 CROSS-PLATFORM TEMPLATE FOR BINARY EXECUTABLE

Making an executable is possible with the L<PAR::Packer> module.
On the Windows platform, threads, threads::shared, and exiting via
threads are necessary for the binary to exit successfully.

 # https://metacpan.org/pod/PAR::Packer
 # https://metacpan.org/pod/pp
 #
 #   pp -o demo.exe demo.pl
 #   ./demo.exe

 use strict;
 use warnings;

 use if $^O eq "MSWin32", "threads";
 use if $^O eq "MSWin32", "threads::shared";

 use Time::HiRes (); # include minimum dependencies for MCE
 use Storable ();

 use IO::FDPass ();  # optional: for MCE::Shared->condvar, handle, queue
 use Sereal ();      # optional: faster serialization, may omit Storable

 use MCE;

 my $mce = MCE->new(
    max_workers => 4,
    user_func => sub {
       print "hello from ", MCE->wid(), "\n";
    }
 );

 $mce->run();

 threads->exit(0) if $INC{"threads.pm"};

With L<MCE::Shared> 1.808 and later releases, L<MCE::Hobo> works just
the same. The following compiles fine on UNIX and the Windows platform.

 # https://metacpan.org/pod/PAR::Packer
 # https://metacpan.org/pod/pp
 #
 #   pp -o demo.exe demo.pl
 #   ./demo.exe

 use strict;
 use warnings;

 use if $^O eq "MSWin32", "threads";
 use if $^O eq "MSWin32", "threads::shared";

 use Time::HiRes (); # include minimum dependencies for MCE::Hobo
 use Storable ();

 use IO::FDPass ();  # optional: for MCE::Shared->condvar, handle, queue
 use Sereal ();      # optional: faster serialization, may omit Storable

 use MCE::Hobo;      # 1.808 or later on Windows
 use MCE::Shared;

 my $seq_a = MCE::Shared->sequence( 1, 30 );

 sub task {
    my ( $id ) = @_;
    while ( defined ( my $num = $seq_a->next ) ) {
       print "$id: $num\n";
    }
 }

 MCE::Hobo->new( \&task, $_ ) for 1 .. 2;
 MCE::Hobo->waitall;

 threads->exit(0) if $INC{"threads.pm"};

=head1 FCGI::PROCMANAGER DEMONSTRATIONS

The demonstrations requires MCE 1.804 to run. Otherwise, the MCE C<posix_exit>
option must be specified and set to 1. This applies to UNIX only and set
automatically in 1.804 when C<(F)CGI.pm> is present.

 #!/usr/bin/perl

 # http://127.0.0.1/cgi-bin/test_mce1.fcgi
 # http://127.0.0.1/cgi-bin/test_mce1.fcgi?size=8

 use strict;
 use warnings;

 use MCE::Map max_workers => 3;

 use CGI::Fast;
 use FCGI::ProcManager;

 my $count = 0;

 my $proc_manager = FCGI::ProcManager->new({ n_processes => 4 });
 $proc_manager->pm_manage();

 while ( my $query = CGI::Fast->new() ) {
    $proc_manager->pm_pre_dispatch();

    print "Content-type: text/html\r\n\r\n";
    print "$$: ", ++$count, "<br>\n";
    print "<hr>\n";

    print "$_ = $ENV{$_}<br>\n" foreach sort keys %ENV;
    print "<hr>\n";

    my %params;

    foreach ( sort $query->param() ) {
       $params{$_} = $query->param($_);
       print $_, " = ", $params{$_}, "<br>\n";
    }

    print "<hr>\n";

    my @ret = mce_map { "$$: ".( $_ * 2 ) } 1 .. $params{'size'} || 8;

    print join("<br>\n", @ret), "<br>\n";

    $proc_manager->pm_post_dispatch();
 }

Initializing MCE options before calling C<pm_manage> is not recommended.
The following is one way to do it and does the same thing.

 #!/usr/bin/perl

 # http://127.0.0.1/cgi-bin/test_mce2.fcgi
 # http://127.0.0.1/cgi-bin/test_mce2.fcgi?size=8

 use strict;
 use warnings;

 use MCE::Map;

 use CGI::Fast;
 use FCGI::ProcManager;

 my ($first_time, $count) = (1, 0);

 my $proc_manager = FCGI::ProcManager->new({ n_processes => 4 });
 $proc_manager->pm_manage();

 while ( my $query = CGI::Fast->new() ) {
    $proc_manager->pm_pre_dispatch();

    print "Content-type: text/html\r\n\r\n";
    print "$$: ", ++$count, "<br>\n";
    print "<hr>\n";

    print "$_ = $ENV{$_}<br>\n" foreach sort keys %ENV;
    print "<hr>\n";

    my %params;

    foreach ( sort $query->param() ) {
       $params{$_} = $query->param($_);
       print $_, " = ", $params{$_}, "<br>\n";
    }

    print "<hr>\n";

    if ( $first_time ) {
       MCE::Map->init( max_workers => 3 );
    }

    my @ret = mce_map { "$$: ".( $_ * 2 ) } 1 .. $params{'size'} || 8;

    print join("<br>\n", @ret), "<br>\n";

    $proc_manager->pm_post_dispatch();
 }

Sharing data is possible via C<MCE::Shared> between C<FCGI> and C<MCE> workers.
The following is a demonstration utilizing a shared counter variable which
increments by one regardless of the C<FCGI> worker serving the request.

 #!/usr/bin/perl

 # http://127.0.0.1/cgi-bin/test_mce3.fcgi
 # http://127.0.0.1/cgi-bin/test_mce3.fcgi?size=8

 use strict;
 use warnings;

 use MCE::Map;
 use MCE::Shared;

 use CGI::Fast;
 use FCGI::ProcManager;

 # Shared variables must be defined before FCGI::ProcManager.
 my $count = MCE::Shared->scalar( 0 );
 my $first_time = 1;

 my $proc_manager = FCGI::ProcManager->new({ n_processes => 4 });
 $proc_manager->pm_manage();

 # Optional, the following statement must come after $pm->pm_manage.
 MCE::Shared->init(); # enables shared parallel-IPC capabilities

 while ( my $query = CGI::Fast->new() ) {
    $proc_manager->pm_pre_dispatch();

    print "Content-type: text/html\r\n\r\n";
    print "$$: ", $count->incr(), "<br>\n";
    print "<hr>\n";

    print "$_ = $ENV{$_}<br>\n" foreach sort keys %ENV;
    print "<hr>\n";

    my %params;

    foreach ( sort $query->param() ) {
       $params{$_} = $query->param($_);
       print $_, " = ", $params{$_}, "<br>\n";
    }

    print "<hr>\n";

    if ( $first_time ) {
       MCE::Map->init( max_workers => 3 );
       $first_time = 0;
    }

    my @ret = mce_map { "$$: ".( $_ * 2 ) } 1 .. $params{'size'} || 8;

    print join("<br>\n", @ret), "<br>\n";

    $proc_manager->pm_post_dispatch();
 }

Resetting the environment is helpful during development. The shared-manager
process stops immediately upon receiving the C<TERM> signal.

 killall -TERM perl-fcgi perl-fcgi-pm ; service httpd restart

=head1 TK DEMONSTRATIONS

The demonstrations requires MCE 1.805 to run. Otherwise, the MCE C<posix_exit>
option must be specified and set to 1. This applies to UNIX only and set
automatically in 1.805 when C<Tk.pm> is present.

 #!/usr/bin/perl

 use strict;
 use warnings;

 use MCE;
 use Tk;

 my $mw = MainWindow->new( -title => 'MCE/Tk Test' );

 $mw->geometry( '300x300' );
 $mw->Button( -text => "Test MCE", -command => \&test_mce )->pack();

 my $frame = $mw->Frame->pack( -fill => 'x' );

 my $mce = MCE->new(
    max_workers => 4,
    user_func => sub {
       my @args = @{ MCE->user_args() };
       print MCE->pid(), ": $_\n";
    },
 )->spawn;

 MainLoop;

 # Do not call $mce->shutdown on Windows ($^O eq 'MSWin32').
 # Workers terminate with the application.
 #
 # $mce->shutdown();

 print "Exiting...\n";

 sub test_mce {
    $mce->process({
       user_args  => [ 'arg1', 'arg2', 'argN' ],
       input_data => [ 1 .. 10 ],
       chunk_size => 1,
    });
 }

The following demonstration does the same thing via MCE::Flow.

 #!/usr/bin/perl

 use strict;
 use warnings;

 use MCE::Flow max_workers => 4;
 use Tk;

 my $mw = MainWindow->new( -title => 'MCE/Tk Test' );

 $mw->geometry( '300x300' );
 $mw->Button( -text => "Test MCE", -command => \&test_mce )->pack();

 my $frame = $mw->Frame->pack( -fill => 'x' );

 sub task {
    my @args = @{ MCE->user_args() };
    print MCE->pid(), ": $_\n";
 }

 MainLoop;

 print "Exiting...\n";

 sub test_mce {
    MCE::Flow->init(
       user_args  => [ 'arg1', 'arg2', 'argN' ],
       chunk_size => 1
    );
    MCE::Flow->run( \&task, [ 1 .. 10 ] );
 }

MCE::Hobo 1.804 or later is another possibility if running on a UNIX platform.

 #!/usr/bin/perl

 use strict;
 use warnings;

 use MCE::Hobo;
 use Tk;

 my $mw = MainWindow->new( -title => 'MCE/Tk Test' );

 $mw->geometry( '300x300' );
 $mw->Button( -text => "Test MCE", -command => \&test_mce )->pack();

 my $frame = $mw->Frame->pack( -fill => 'x' );

 sub task {
    my @args = @_;
    print MCE::Hobo->pid(), ": $_\n";
 }

 MainLoop;

 print "Exiting...\n";

 sub test_mce {
    MCE::Hobo->create(\&task, 'arg1', 'arg2', 'argN') for ( 1 .. 4 );
    MCE::Hobo->waitall();
 }

=head1 INDEX

L<MCE|MCE>, L<MCE::Core>

=head1 AUTHOR

Mario E. Roy, S<E<lt>marioeroy AT gmail DOT comE<gt>>

=cut