blib/lib/PDL/Parallel/threads/SIMD.pm untested

filter: Statementstmt 0.0% 0 / 59 Branchbran 0.0% 0 / 10 Conditioncond 0.0% 0 / 6 MC/DCmcdc 0.0% 0 / 4 Subroutinesub 0.0% 0 / 12 Podpod 0.0% 0 / 5 totaltotal 0.0% 0 / 96 CC 6 SCAR 20.8
CC
6
Cov
0%
parallel_sync
20.0
parallelize
12.0
parallel_id
2.0
CRAP 8.0
1 package PDL::Parallel::threads::SIMD;
2  
3 use strict;
4 use warnings;
5 use Carp;
6  
7 our $VERSION = '0.02';
8  
9 require Exporter;
10 our @ISA = qw(Exporter);
11  
12  
13 our @EXPORT_OK = qw(parallelize parallel_sync parallel_id);
14  
15 use threads qw(yield);
16 use threads::shared qw(cond_wait);
17  
18 our $N_threads = -1;
19  
20 ################
21 # barrier_sync #
22 ################
23  
24 our $barrier_count :shared = 0;
25 our $barrier_state :shared = 'ready';
26  
27 sub parallel_sync () {
28 if ($N_threads < 1) {
29 carp("Cannot call parallel_sync outside of a parallelized block");
30 return;
31 }
32  
33 yield until $barrier_state eq 'ready' or $barrier_state eq 'up';
34  
35 lock($barrier_count);
36 $barrier_state = 'up';
37 $barrier_count++;
38  
39 if ($barrier_count == $N_threads) {
40 $barrier_count--;
41 $barrier_state = 'down';
42 cond_broadcast($barrier_count);
43 yield;
44 }
45 else {
46 cond_wait($barrier_count) while $barrier_state eq 'up';
47 $barrier_count--;
48 $barrier_state = 'ready' if $barrier_count == 0
49 }
50 }
51  
52 sub parallel_id () {
53 goto \&get_tid;
54 }
55  
56 sub get_tid {
57 carp("Cannot get parallel_id outside of a parallelized block");
58 }
59  
60 ##################
61 # SIMD launching #
62 ##################
63  
64 sub run_it {
65 my ($tid, $subref) = @_;
66 no warnings 'redefine';
67 local *get_tid = sub { $tid };
68 $subref->();
69 parallel_sync;
70 }
71  
72 # Takes a block, the number of threads, and any thread arguments
73 sub parallelize (&$) {
74 my ($sub, $requested_threads,) = @_;
75 # For now, prevent nested launches
76 croak("Cannot nest parallelized blocks (yet)")
77 unless $N_threads == -1;
78 croak("Must request a positive number of parallelized threads")
79 unless $requested_threads =~ /^\d/ and $requested_threads > 0;
80 # This does not need to be localized once nested launches gets
81 # figured out. But for now, localize it so it gets restored to -1 at
82 # the end of the function call.
83 local $N_threads = $requested_threads;
84 # local $barrier_count = 0;
85 # local $barrier_state = 'ready';
86  
87 # Launch N-1 threads...
88 my @to_join = map {
89 threads->create(\&run_it, $_, $sub)
90 } (1..$N_threads-1);
91 # ... and execute the last thread in this, the main thread
92 run_it(0, $sub);
93  
94 # Reap the threads
95 for my $thr (@to_join) {
96 $thr->join;
97 }
98 }
99  
100 1;
101  
102 __END__