blib/lib/Thread/DependentJobs.pm untested

filter: Statementstmt 0.0% 0 / 555 Branchbran 0.0% 0 / 266 Conditioncond 0.0% 0 / 120 MC/DCmcdc 0.0% 0 / 70 Subroutinesub 0.0% 0 / 49 Podpod 0.0% 0 / 31 totaltotal 0.0% 0 / 1091 CC 134 SCAR 48.2
CC
134
Cov
0%
_enqueue_if_ready
506.0
_run_job
272.0
wait
156.0
CRAP 124.0
1 use strict; use warnings; use feature qw(say state signatures);
2 # vi:set ai expandtab ts=4:
3  
4 package Thread::DependentJobs;
5  
6 our @ISA = qw/Exporter/;
7 our @EXPORT = ();
8 our @EXPORT_OK = qw/my_jobid/;
9  
10 { no strict 'refs'; ${__PACKAGE__."::VER"."SION"} //= 997.999; }
11 our $VERSION = '1.3'; # VERSION from Dist::Zilla::Plugin::OurPkgVersion
12 our $DATE = '2026-11-18'; # DATE from Dist::Zilla::Plugin::OurDate
13  
14 use threads;
15 use threads::shared;
16 use Thread::Queue;
17 use List::Util qw/all any/;
18 use List::MoreUtils qw/firstidx/;
19 use Scalar::Util 1.10 qw(looks_like_number blessed);
20 use Carp;
21 use Data::Dumper::Interp qw/visnew vis visq viso avis hvis
22 dvis dviso ivis visr addrvis u qsh qshlist/;
23 use Spreadsheet::Edit::Log qw/:btw oops get_logdest/;
24 use File::Basename qw/basename/;
25 use Guard qw/scope_guard/;
26 use overload ();
27  
28 use constant SEMA_PKG => __PACKAGE__."::sema";
29  
30 # Remember Job Schedulers for cleanup in the main thread's END{}
31 # ('threads' doc warns thread ops within a thread-specific END
32 # may deadlock; I hope this is not a problem for main thread's END)
33 our %schedulers :shared; # uniqeuid => { ... }
34 our $sseq :shared = 0;
35  
36 $SIG{SEGV} = sub($sig,@) { btwbt "Caught $sig"; _exit(9); };
37 $SIG{TERM} =
38 $SIG{QUIT} =
39 $SIG{INT} = sub($sig,@) { btwbt "Interrupted by SIG$sig"; };
40  
41 # global Configure options
42 my $allserial :shared = 0;
43 our $debug = 0; # not shared for speed; set in new() before creating threads
44  
45 our $warnlock : shared;
46 sub _install_warn_hook() {
47 my $origwarn = $SIG{__WARN__};
48 $SIG{__WARN__} = sub {
49 lock $warnlock;
50 ($origwarn || \&CORE::warn)->(@_);
51 };
52 }
53  
54 our $curr_jobid = undef; # not shared, but per-thread
55 our $curr_job; # not shared, but per-thread
56  
57 sub _is_stringish($thing) {
58 my $class;
59 defined($thing) && (
60 (ref($thing) eq "")
61 ||
62 (defined($class = blessed($thing)) && overload::Method($class,'""'))
63 )
64 }
65  
66 my $global_initialized;
67 sub _global_init() {
68 _check_on_main_thread();
69  
70 lock %schedulers;
71  
72 if (! $global_initialized) {
73 _install_warn_hook();
74 $global_initialized = 1;
75 }
76 }
77 sub _check_on_main_thread() {
78 confess "Should only be called by the main thread\n"
79 unless threads->tid() == 0;
80 }
81  
82 sub fmt_jobid($self, $jobid, $longform=1) { # %$self must be locked
83 oops unless defined($jobid);
84 my $finished = "";
85 my $job = $self->{JOBS}->{$jobid};
86 if (! $job) {
87 $job = $self->{FINISHED_JOBS}->{$jobid} // oops;
88 $finished = " (finished)";
89 }
90 my ($subname,$args,$inputs,$outputs) = @$job{qw/subname args inputs outputs/};
91 oops dvis '$jobid $job $self->{JOBS} $self->{FINISHED_JOBS}' unless defined $subname;
92 $longform
93 ? "$jobid: $subname(args=>".vis($args).",inputs=>".vis($inputs).",outputs=>".vis($outputs).")$finished"
94 : "$jobid: $subname(...)$finished"
95 }
96  
97 sub _get_Semaphore_id($s) {
98 # Return the shared-object id (breaking encapsulation of Thread::Semaphore)
99 is_shared($s) // oops dvis '$s';
100 }
101 sub _get_Semaphore_val($s) {
102 # Breaking encapsulation of Thread::Semaphore. Just for debug messages!
103 $$s
104 }
105  
106 sub _fmt_sema($sema) {
107 oops unless defined $sema;
108 my ($s, $down_count, $up_count) = @$sema;
109 my $id = _get_Semaphore_id($s);
110 my $msg;
111 if ($down_count == $up_count) {
112 if ($down_count == 1) {
113 $msg = "Semaphore<$id>";
114 } else {
115 $msg = "[Semaphore<$id>, $down_count]";
116 }
117 } else {
118 $msg = "[Semaphore<$id>, $down_count, $up_count]";
119 }
120 $msg." (current:"._get_Semaphore_val($s).")";
121 }
122  
123 # Create a token info hash, if it does not already exist,
124 # at $self->{TOKENS}->{tokname} .
125 # Throws an error if the tokname is invalid.
126 # If jobid_if_output is given, sets or updates {PRODUCER_JOBID}
127 # if it is not already set (or the token is new), but
128 # Throws an error the token already exists with PRODUCER_JOBID set.
129 # Returns a ref to the tokinfo hash
130 sub _get_tokinfo($self, $tokname, $jobid_if_output=undef) {
131 # %$self must be locked!
132 if (! _is_stringish($tokname)) {
133 confess "Token '",u($tokname),"' is not a string";
134 }
135 my $tokinfo = $self->{TOKENS}->{$tokname};
136 if ($tokinfo) {
137 if ($jobid_if_output && (my $producer=$tokinfo->{PRODUCER_JOBID})) {
138 confess "Attempt to re-use output token '$tokname'\n",
139 "(it is already an output for job $producer)\n";
140 }
141 } else {
142 $tokinfo = $self->{TOKENS}->{$tokname} = &share({});
143 $tokinfo->{WAITING} = &share([]);
144 }
145 $tokinfo->{PRODUCER_JOBID} = $jobid_if_output if $jobid_if_output;
146 return $tokinfo;
147 }
148  
149 sub Configure :prototype($@) ($class, @args) {
150 oops unless eval{ $class->isa(__PACKAGE__) };
151 my %opts = (@args==1 ? (%{$args[0]}) : @args);
152 _check_on_main_thread();
153 foreach (keys %opts) {
154 # Previously we used a common thread pool for all Job Schedulers
155 # and so NUMTHREADS was accepted here. No longer.
156 if (/^DEBUG$/) { $debug = delete $opts{$_}; }
157 elsif (/^ALLSERIAL$/) { $allserial = delete $opts{$_}; }
158 else { croak "Invalid Thread::DependentJob->Configure option '${_}'\n"; }
159 }
160 die if %opts;
161 _global_init();
162 }
163  
164 sub new($class, %options) {
165 $class = ref($class) || $class;
166 if (exists $options{DEBUG}) {
167 $debug = delete $options{DEBUG}; # global, affects all Job Schedulers
168 }
169 _global_init();
170  
171 # c.f. https://api.metacpan.org/source/JDHEDDEN/threads-shared-1.59/examples/class.pl
172 share(my %hash);
173 $hash{TIDS} = &share([]);
174 $hash{JOBS} = &share({}); # incomplete jobs
175 $hash{FINISHED_JOBS} = &share({}); # jobid => { JOBS hash plus RESULT }
176 $hash{QUEUED} = &share({}); # jobid => 1
177 $hash{TOKENS} = &share({}); # all tokens we ever heard of:
178 # tokname => { PRODUCER_JOBID => ...
179 # POISONED => boolean
180 # WAITING => [jobids waiting for it]
181 # }
182 $hash{QUEUE} = shared_clone( Thread::Queue->new() );
183 $hash{JSEQ } = 0;
184  
185 my $numthreads = delete $options{NUMTHREADS};
186 if (! defined $numthreads) {
187 my $numcpus = $ENV{NUMBER_OF_PROCESSORS}
188 || (`grep "processor\t:" /proc/cpuinfo | wc -l`)
189 || 1;
190 chomp $numcpus;
191 $numthreads = $numcpus + 1;
192 }
193 croak "Unknown ",__PACKAGE__,"->new option '$_'" for keys %options;
194  
195 my $obj = bless(\%hash, $class);
196  
197 lock %schedulers;
198 $obj->{SNUM} = $sseq++;
199 my $jobschid = "js".$obj->{SNUM};
200 oops if exists $schedulers{$jobschid};
201 $schedulers{$jobschid} = $obj;
202 $obj->{WSID} = $jobschid;
203  
204 while (@{$obj->{TIDS}} < $numthreads) { # zero is allowed
205 my $thr = threads->create({context => 'void'}, \&_thread_main, $jobschid);
206 confess "threads->create failed ($!)" unless $thr;
207 my $tid = $thr->tid();
208 push @{$obj->{TIDS}}, $tid;
209 }
210  
211 warn ">>> $obj: Created Job Scheduler with ",scalar(@{$obj->{TIDS}})," threads.\n" if $debug;
212 return $obj;
213 }#new
214  
215 sub get_numthreads($self) { scalar( @{ $self->{TIDS} } ) }
216  
217 sub _canon_sema($sema) {
218 if (blessed($sema) && $sema->isa("Thread::Semaphore")) {
219 $sema = [$sema, 1];
220 }
221 elsif (ref($sema) eq "ARRAY" && (@$sema==2 || @$sema==3)
222 && blessed($$sema[0]) && $$sema[0]->isa("Thread::Semaphore")
223 && (all{ looks_like_number($_) && int($_)==$_ && $_ >= 0 } @$sema[1..$#$sema])
224 ) {
225 # already [semaphore,count] or [semaphore,upcount,downcount]
226 }
227 else {
228 confess "Invalid sema ",visnew->vis($sema);
229 }
230 if (@$sema==2) { push @$sema, $sema->[1] } # [sem,N] --> [sem,N,N]
231 return shared_clone($sema);
232 }
233  
234 sub sched($self, %opts) {
235 my $mytid = threads->tid();
236  
237 share(my %job);
238  
239 my $subname = delete($opts{subname}) // croak "'subname' is required";
240 $subname = (caller)[0]."::".$subname unless $subname =~ /:/;
241 $job{subname} = $subname;
242  
243 my $context = delete($opts{context}) // (wantarray ? "list" : "scalar");
244 croak "context value must be 'list', 'scalar' or 'void' (not '$context')\n"
245 unless $context =~ /^(?:list|scalar|void)$/;
246 $job{context} = $context;
247  
248 for my $key (qw/args inputs outputs/) {
249 $job{$key} = shared_clone( delete($opts{$key}) // [] );
250 }
251 $job{semas} = shared_clone( [
252 # sort by mem addr to avoid deadlock
253 sort{ _get_Semaphore_id($a->[0]) <=> _get_Semaphore_id($b->[0]) }
254 map{ _canon_sema($_) }
255 @{ delete($opts{semas}) // [] }
256 ] );
257  
258 croak "Unknown option '$_'\n" for (keys %opts);
259  
260 my $jobid;
261 { lock $self;
262  
263 # Canonical jobids are "J<scheduler_number>.<job_number>" but omit the
264 # scheduler number on the first (typically only) Job Scheduler instantiation
265 my ($snum, $jnum) = ($self->{SNUM}, $self->{JSEQ}++);
266 $jobid = "J".($snum==0 ? "" : "${snum}.").$jnum;
267 $job{JOBID} = $jobid;
268 $self->{JOBS}->{$jobid} = \%job;
269  
270 # Register tokens, checking for errors
271 foreach my $tokname (@{ $job{inputs} }) {
272 my $tokinfo = _get_tokinfo($self, $tokname, undef);
273 push @{ $tokinfo->{WAITING} }, $jobid;
274 }
275 foreach my $tokname (@{ $job{outputs} }) {
276 _get_tokinfo($self, $tokname, $jobid);
277 }
278  
279 btwN \3, "### [$mytid] Scheduling ",$self->fmt_jobid($jobid),"\n" if $debug;
280  
281 $self->_enqueue_if_ready([$jobid]);
282 }
283 threads->yield();
284  
285 $jobid;
286 }#sched
287  
288 sub _run_queue_directly($self) {
289 # ?? do we need to worry about delete() being called concurrently?
290 my $q = $self->{QUEUE};
291 if ($q->pending) {
292 warn "### serial mode, running jobs on main thread\n" if $debug;
293 while (defined (my $jobid = $q->dequeue_nb())) {
294 $self->_run_workitem($jobid);
295 }
296 }
297 }
298  
299 sub wait($self) {
300 confess "Must be called on a Job Scheduler *OBJECT*\n" unless ref($self);
301 lock $self;
302 my $mytid = threads->tid();
303 btwN \3, ">>> [$mytid] Starting wait $self" if $debug;
304 while (keys %{ $self->{JOBS} }) {
305 if( @{$self->{TIDS}} == 0 ) {
306 $self->_run_queue_directly;
307 # We can detect deadlock in serial mode!
308 if (my @lines = $self->_unfinished_job_info) {
309 confess "DEADLOCK? Some job(s) never ran:\n", @lines;
310 }
311 last;
312 } else {
313 if ($debug) {
314 my @jobids = keys %{$self->{JOBS}};
315 btwbt ">>> [$mytid] wait: cond_wait %{ ",addrvis($self),"} (current jobs: @jobids) ...\n";
316 }
317 cond_wait %$self; # cond_broadcast at end of _run_job
318 btwbt ">>> [$mytid] back from cond_wait" if $debug;
319 }
320 }
321 $self->_abort_if_jobs_remain;
322  
323 # Return hash mapping
324 # jobid => {inputs=>[...], outputs=>[...], result=> scalar} }
325 my $result = $self->{FINISHED_JOBS};
326 $self->{FINISHED_JOBS} = shared_clone({});
327  
328 if (!defined wantarray) {
329 # results not being checked -- warn of aborted jobs
330 for my $jobid (keys %$result) {
331 my $job = $result->{$jobid};
332 oops unless $job->{JOBID} eq $jobid;
333 if (my $msg = $job->{ABORTMSG}) {
334 chomp $msg;
335 warn "Jobid $jobid : $msg\n";
336 } else {
337 oops if $job->{EXCEPTION};
338 }
339 }
340 }
341 btwbt ">>> [$mytid] wait returning ${\(visnew->Refaddr(1)->vis($result))}" if $debug;
342 return $result
343 }
344  
345 sub abort_job($self, $jobid, $msg="") {
346 lock $self;
347 $msg = ":$msg" if $msg;
348 my $job = $self->{JOBS}->{$jobid};
349 if (! $job) {
350 return 1 if exists $self->{FINISHED_JOBS}->{$jobid};
351 confess "abort_job: $jobid is not defined\n";
352 }
353 if (my $tid = $job->{TID}) {
354 btwbt ">>> abort_job: KILLING ",$self->fmt_jobid($jobid,0)," on tid $tid\n" if $debug;
355 $job->{ABORTMSG} //= "[killed by abort_job${msg}]";
356 threads->object($tid)->kill('SIGTERM');
357 } else {
358 btwbt ">>> abort_job: CANCELLING ",$self->fmt_jobid($jobid,0)," ...\n" if $debug;
359 $job->{ABORTMSG} //= "[cancelled before running by abort_job${msg}]";
360 $self->_enqueue_if_ready([$jobid]) unless $self->{QUEUED}->{$jobid};
361 }
362 # The job still exists; you must call 'wait' to clean it up.
363 #
364 # If executing, the job was signaled and will stop promptly.
365 # If still queued, it will start as soon as a worker thread becomes
366 # available and then immediately abort without calling the user's code.
367 return 0;
368 }
369  
370 sub delete_tokens($self, @toknames_to_delete) {
371 lock $self;
372 my $my_jobid = my_jobid()//"";
373 foreach my $job (values %{$self->{JOBS}}) {
374 if ($job->{JOBID} ne $my_jobid) { # ok to delete our own input
375 foreach my $tokname (@{$job->{inputs}}) {
376 if (any{ $_ eq $tokname } @toknames_to_delete) {
377 croak "Can not delete token '$tokname' because it is an input token for unfinished job $job->{JOBID}";
378 }
379 }
380 foreach my $tokname (@{$job->{outputs}}) {
381 if (any{ $_ eq $tokname } @toknames_to_delete) {
382 croak "Can not delete token '$tokname' because it is an output token for unfinished job $job->{JOBID}";
383 }
384 }
385 }
386 }
387 for my $tokname (@toknames_to_delete) {
388 my $tokinfo = $self->{TOKENS}->{$tokname}
389 // croak "'$tokname' is an unknown token name";
390 if (! $tokinfo->{PRODUCED}) {
391 oops dvis 'BUG: $tokname was never PRODUCED\n$tokinfo';
392 }
393 for my $dependent (grep{defined} @{ $tokinfo->{WAITING} }) {
394 oops dvis 'BUG: $tokname : $dependent is WAITING \n$tokinfo';
395 }
396 if (exists $tokinfo->{POISONED}) {
397 # nothing special to do?
398 }
399 oops "unimplemented" ### FIXME
400 }
401 }
402  
403 sub all_jobids($self) {
404 lock $self;
405 return( keys %{$self->{JOBS}}, keys %{$self->{FINISHED_JOBS}} );
406 }
407  
408 # Wait for any remaining jobs to complete, shut down threads, and delete
409 # internal references to the object
410 sub delete($self) {
411 my $tid = threads->tid();
412 btw ">>> [$tid] Starting delete of ${\addrvis($self)} ...\n" if $debug;
413 my @worker_tids;
414 { lock $self;
415 oops "[$tid] Already deleted ($self->{DESTROYED})!" if $self->{DESTROYED};
416 $self->{DESTROYED} = "started";
417 @worker_tids = @{$self->{TIDS}};
418 }
419 # Calling wait in void context so it will warn of abnormally-terminated jobs.
420 $self->wait(); # wait for jobs to run and finish
421 { lock $self;
422 for (1..@{$self->{TIDS}}) {
423 $self->{QUEUE}->enqueue(undef); # send EOF, one per thread
424 }
425 }
426 foreach my $tid (@worker_tids) {
427 my $thr = threads->object($tid);
428 oops if $thr->is_detached();
429 btw ">>> joining tid $tid ...\n" if $debug;
430 $thr->join();
431 btw ">>> tid $tid has joined\n" if $debug;
432 }
433 oops dviso '$self' if keys %{$self->{QUEUED}};
434 oops dviso '$self' if keys %{$self->{JOBS}};
435 oops dviso '$self' if keys %{$self->{FINISHED_JOBS}};
436 oops dviso '$self' if $self->{QUEUE}->pending() != 0;
437 $self->{DESTROYED} = "finished";
438 lock %schedulers;
439 delete $schedulers{$self->{WSID}} // oops;
440 }
441  
442 sub _has_unfinished_jobs($self) {
443 $self->_run_queue_directly if @{$self->{TIDS}} == 0;
444 lock $self;
445 return scalar %{ $self->{JOBS} }
446 }
447 sub _unfinished_job_info($self) {
448 # Returns a list of strings, one per waiting job
449 $self->_run_queue_directly if @{$self->{TIDS}} == 0;
450 my @result;
451 lock $self;
452 foreach my $jobid (keys %{$self->{JOBS}}) {
453 my $job = $self->{JOBS}->{$jobid};
454 my @unsatisfied_inputs;
455 foreach my $tokname (@{$job->{inputs}}) {
456 my $tokinfo = $self->{TOKENS}->{$tokname} // oops;
457 if (! $tokinfo->{PRODUCED}) {
458 push @unsatisfied_inputs, $tokname;
459 }
460 }
461 if (@unsatisfied_inputs) {
462 push @result, $self->fmt_jobid($jobid,0)
463 ." has unsatisfied inputs (never produced): "
464 .join(", ", @unsatisfied_inputs)
465 ."\n";
466 }
467 elsif ($self->{QUEUED}->{$jobid}) {
468 push @result, $self->fmt_jobid($jobid,0)
469 ." is enqueued, waiting for a free thread.\n";
470 }
471 elsif (my $tid = $job->{TID}) {
472 push @result, $self->fmt_jobid($jobid,0)
473 ." is currently executing on tid $tid.\n";
474 }
475 else {
476 confess "[${\(threads->tid)}] bug: bad state for $jobid (no unsatisfied inputs)\n",
477 visnew->dviso('$self\n');
478 }
479 }
480 return @result;
481 }
482  
483 sub _abort_if_jobs_remain($self) {
484 lock $self;
485 if (%{ $self->{JOBS} }) {
486 my @descrips = $self->_unfinished_job_info();
487 oops unless @descrips; # jobs remain but none are waiting for anything
488 # Nevertheless, I think this still implies a bug in Job Scheduler!
489 confess "Some job(s) never ran:\n", @descrips;
490 }
491 }
492  
493 END{
494 local($., $@, $!, $^E, $?);
495 btw ">>> Starting Job Scheduler END block (PHASE ${^GLOBAL_PHASE})\n" if $debug;
496  
497 _check_on_main_thread();
498  
499 # Circular or cross-thread references to Job Scheduler objects would often
500 # prevent automatic cleanup via DESTROY, and weak references don't work
501 # in shared data. So instead we keep a global list of all Job Scheduler
502 # objects and clean up here.
503  
504 for(;;) {
505 lock %schedulers;
506 if ((my @wsids = keys %schedulers)) {
507 for my $jobschid (@wsids) {
508 my $jobsch = $schedulers{$jobschid};
509 $jobsch->delete();
510 }
511 } else {
512 last;
513 }
514 threads->yield;
515 # Repeat in case a job created a new Job Scheduler (really allowed?)
516 }
517  
518 btw ">>> Leaving Job Scheduler END block\n" if $debug;
519 }#END
520  
521 #INTERNAL
522 sub _enqueue_if_ready ($self, $jobids) { # Job Scheduler must be locked
523 my $tid = threads->tid();
524  
525 my %jobid2ready; # 0 if still waiting, 1 if ready to start
526 JOB:
527 foreach my $jobid (@$jobids) {
528 # @$jobids may include the same value several times
529 next if exists $jobid2ready{$jobid};
530 $jobid2ready{$jobid} = 0;
531  
532 my $job = $self->{JOBS}->{$jobid} // oops;
533  
534 my @unavail_semas;
535 my @unavail_inputs;
536 my @got_semas;
537 CHECK: {
538 last CHECK if $job->{ABORTMSG};
539 foreach my $tokname (@{$job->{inputs}}) {
540 my $tokinfo = $self->{TOKENS}->{$tokname} // oops;
541 if (exists $tokinfo->{POISONED}) {
542 $job->{ABORTMSG} = "[cancelled: need '$tokname' from aborted job $tokinfo->{PRODUCER_JOBID}]";
543 btw "Start ${jobid}: input token '$tokname' was poisoned\n" if $debug;
544 last;
545 }
546 elsif ($tokinfo->{PRODUCED}) {
547 btw "Start ${jobid}: input '$tokname' is ready\n" if $debug;
548 }
549 else {
550 push @unavail_inputs, $tokname;
551 last CHECK unless $debug; # check all if tracing
552 btw "Start ${jobid}: input '$tokname' is has not yet been produced\n" if $debug;
553 }
554 }
555 foreach my $sema (@{$job->{semas}}) {
556 my ($s, $down_count, $up_count) = @$sema;
557 next if $down_count == 0;
558 if ($s->down_nb($down_count)) {
559 push @got_semas, $sema;
560 btw "Start ${jobid}: \"downed\" ", _fmt_sema($sema),"\n" if $debug;
561 } else {
562 push @unavail_semas, $sema;
563 btw "Start ${jobid}: COULD NOT \"down\" ", _fmt_sema($sema),"\n" if $debug;
564 last CHECK unless $debug; # check all if tracing
565 }
566 }
567 # semas will be "up"d in _wrapup_job
568 }
569 if (@unavail_inputs or @unavail_semas or $job->{ABORTMSG}) {
570 for my $sema (@got_semas) {
571 my ($s, $down_count) = @$sema;
572 $s->up($down_count); # un-do
573 btw "Start ${jobid}: \"un-downed\" (due to unready condition) ", _fmt_sema($sema),"\n" if $debug;
574 }
575 if ($job->{ABORTMSG}) {
576 $self->_wrapup_job($job, 0);
577 next JOB;
578 }
579 if ($debug) {
580 foreach (@unavail_semas) {
581 warn "$jobid is waiting for ", _fmt_sema($_);
582 }
583 foreach my $tokname (@unavail_inputs) {
584 warn "$jobid is waiting for input '$tokname'\n";
585 }
586 }
587 next JOB
588 if (@unavail_semas or @unavail_inputs);
589 # Aborted jobs are queued and fake-executed...
590  
591 }
592  
593 btwbt "### [$tid] Enqueuing ",$self->fmt_jobid($jobid,0),"\n" if $debug;
594  
595 oops if $self->{QUEUED}->{$jobid};
596 $self->{QUEUED}->{$jobid} = 1;
597  
598 # Zap (set to undef) the entry in token WAITING lists for this job
599 # (faster than squishing, and shared arrays don't support splice())
600 foreach my $tokname (@{$job->{inputs}}) {
601 my $tokinfo = $self->{TOKENS}->{$tokname};
602 my $ix = firstidx{ defined($_) && $_ eq $jobid } @{ $tokinfo->{WAITING} };
603 oops if $ix < 0;
604 $tokinfo->{WAITING}->[$ix] = undef;
605 }
606  
607 my $q = $self->{QUEUE};
608 $q->enqueue($jobid);
609 }
610 }#_enqueue_if_ready
611  
612 #INTERNAL
613 sub _set_aborted_job_result($job) {
614 oops if exists $job->{RESULT};
615 my $context = $job->{context} // oops;
616 $job->{RESULT} = shared_clone( $context eq "list" ? [] : undef )
617 unless $context eq "void";
618 }
619  
620 # Call user's code (unless ABORTMSG is set) with a signal handler, etc.
621 # job->{TID} is set around the call and removed before returning.
622 sub _call_usersub($self, $tid, $job) {
623 local $SIG{__WARN__} = $SIG{__WARN__};
624 local $SIG{__DIE__} = $SIG{__DIE__};
625 # localize these to simulate thread effects in SERIAL mode
626 local $curr_jobid = $job->{JOBID} // oops;
627 local $curr_job = $job;
628 $@ = "";
629  
630 scope_guard {
631 lock $self;
632 delete $job->{TID};
633 };
634  
635 local $SIG{'TERM'} = sub ($sig,@) {
636 lock $self;
637 $job->{KILLED} = 1;
638 die "$curr_jobid aborted (caught SIG${sig})\n";
639 };
640  
641 my $subname = $job->{subname} // oops viso($job);
642 { lock $self;
643 oops if $job->{KILLED};
644 oops if exists $job->{TID};
645 oops dviso('$self') unless delete $self->{QUEUED}->{$curr_jobid};
646 return
647 if $job->{ABORTMSG};
648 $job->{TID} = $tid;
649 }
650  
651 # user's sub is called in whatever context we are called in
652 no strict 'refs';
653 &$subname(js => $self,
654 args => $job->{args},
655 inputs => $job->{inputs},
656 outputs => $job->{outputs},
657 );
658 }
659  
660 sub _run_job($self, $jobid) {
661 my $tid = threads->tid();
662  
663 my ($job, $context);
664 { lock $self;
665 $job = $self->{JOBS}->{$jobid} // oops;
666 $context = $job->{context};
667 btw "[$tid] EXECUTING ",$self->fmt_jobid($jobid,0),"\n" if $debug;
668 confess "bug" if defined $curr_job;
669 }
670  
671 # _call_usersub returns immediately if ABORTMSG is set.
672 my $result;
673 if ($context eq "void") {
674 eval{ $self->_call_usersub($tid, $job); };
675 $result = "(nothing:void context)";
676 }
677 elsif ($context eq "scalar") {
678 $result = eval{ $self->_call_usersub($tid, $job); };
679 }
680 elsif ($context eq "list") {
681 $result = [ eval{ $self->_call_usersub($tid, $job); } ];
682 }
683 else { oops };
684  
685 lock $self;
686 my $abortmsg = $job->{ABORTMSG};
687 unless ($abortmsg) {
688 $abortmsg = "[killed]" if $job->{KILLED};
689 if (my $ex = $@) {
690 $job->{EXCEPTION} = shared_clone($ex);
691 if (ref($ex)) {
692 $abortmsg //= "[die called with object or other non-scalar]";
693 } else {
694 chomp $ex;
695 $abortmsg //= "[died: $ex]";
696 }
697 }
698 if ($debug && !$abortmsg) {
699 btw "[$tid] $jobid ",$job->{subname}," returned ",vis($result)," ($context context)\n";
700 }
701 }#not already aborting
702  
703 oops dvis '$job' if exists $job->{RESULT};
704 if ($abortmsg) {
705 btw "### [$tid] $jobid : ABORTMSG:=$abortmsg\n" if $debug;
706 $job->{ABORTMSG} = $abortmsg;
707 # setting $result to an explanatory string looks nice for debugging,
708 # but violates the API which says undef or [] will be returned for
709 # aborted or cancelled jobs.
710 #$result = $abortmsg;
711 _set_aborted_job_result($job);
712 } else {
713 $job->{RESULT} = shared_clone($result) unless $context eq "void";
714 }
715 $self->_wrapup_job($job, 1);
716  
717 if ($debug) {
718 my @jobids = keys %{$self->{JOBS}};
719 btw "### [$tid] $jobid cond_broadcast ",addrvis($self);
720 }
721 cond_broadcast %$self;
722 }#_run_job_
723  
724 sub _wrapup_job($self, $job, $up_semas) {
725 # $self must be locked
726 my $jobid = $job->{JOBID};
727 my $abortmsg = $job->{ABORTMSG};
728  
729 my @dependent_jobids; # dups ok
730  
731 foreach my $tokname (@{ $job->{outputs} }) {
732 my $tokinfo = $self->{TOKENS}->{$tokname} // oops;
733 oops dvis '$tokinfo' unless $tokinfo->{PRODUCER_JOBID} eq $jobid;
734 oops if exists $tokinfo->{PRODUCED};
735 $tokinfo->{PRODUCED} = 1;
736 push @dependent_jobids, grep{defined} @{ $tokinfo->{WAITING} };
737  
738 if ($abortmsg) {
739 $tokinfo->{POISONED} = 1;
740 btw "'$tokname' POISONED by ", $self->fmt_jobid($jobid), ":$abortmsg\n" if $debug;
741 } else {
742 btw "'$tokname' produced by ", $self->fmt_jobid($jobid), "\n" if $debug;
743 }
744 }
745 if ($up_semas) {
746 foreach my $sema (@{$job->{semas}}) {
747 my ($s, $down_count, $up_count) = @$sema;
748 if ($up_count != 0) {
749 btw "${jobid} done: \"upping\" ", _fmt_sema($sema),"\n" if $debug;
750 $s->up($up_count);
751 }
752 }
753 }
754 oops if $self->{FINISHED_JOBS}->{$jobid};
755 delete( $self->{JOBS}->{$jobid} );
756 $self->{FINISHED_JOBS}->{$jobid} = $job;
757  
758 $self->_enqueue_if_ready(\@dependent_jobids);
759 }#_wrapup_job
760  
761 sub my_jobid {
762 # This actually can be called as a class method, object method,
763 # or plain function
764  
765 #confess "my_jobid() may only be called from an executing job\n"
766 # unless defined $my_jobid;
767 return $curr_jobid;
768 }
769 sub _thread_main($jobschid) {
770 _install_warn_hook();
771 my $jobsch = $schedulers{$jobschid} // oops;
772 btwbt "tid ",threads->tid(),ivis ': _thread_main($jobschid) starting...\n' if $debug;
773 my $queue = $jobsch->{QUEUE};
774 for (;;) {
775 btwbt "[",threads->tid(),"] dequeue... (curr. ",
776 $queue->pending()," items)" if $debug;
777 my $jobid = $queue->dequeue();
778 last if ! defined $jobid;
779 btw "[",threads->tid(),"] dequeued $jobid" if $debug;
780 $jobsch->_run_job($jobid);
781 }
782 btw "[",threads->tid(),"] EOF msg from queue\n" if $debug;
783 }
784  
785 1;
786  
787 __END__