blib/lib/Thread/Queue/Multiplex.pm untested

filter: Statementstmt 0.0% 0 / 416 Branchbran 0.0% 0 / 136 Conditioncond 0.0% 0 / 68 MC/DCmcdc 0.0% 0 / 41 Subroutinesub 0.0% 0 / 57 Podpod 0.0% 0 / 38 totaltotal 0.0% 0 / 756 CC 69 SCAR 29.6
CC
69
Cov
0%
unsubscribe
72.0
_lock_load
42.0
respond
42.0
CRAP 19.3
1 package Thread::Queue::Multiplex;
2 #
3 # Copyright(C) 2005, 2006, Dean Arnold, Presicient Corp., USA
4 #
5 # Permission is granted to use this software according to the
6 # terms of the Perl Artistic License, as
7 # specified in the Perl README file.
8 #
9 # A subclass of Thread::Queue::Duplex to support
10 # publish/subscribe communications for threads
11 #
12 require 5.008;
13  
14 use threads;
15 use threads::shared;
16 use Thread::Queue::Queueable;
17 use Thread::Queue::Duplex;
18  
19 use base qw(Thread::Queue::Duplex);
20  
21 use strict;
22 use warnings;
23  
24 our $VERSION = '0.92';
25  
26 =head1 NAME
27  
28 Thread::Queue::Multiplex (I<aka> TQM) - thread-safe publish/subscribe queue
29  
30 =begin html
31  
32 <a href='http://www.presicient.com/tqm/Thread-Queue-Multiplex-0.91.tar.gz'>Thread-Queue-Multiplex-0.91.tar.gz</a>
33  
34 =end html
35  
36 =head1 SYNOPSIS
37  
38 use Thread::Queue::Multiplex;
39 #
40 # create new queue, limiting the max pending requests
41 # to 20
42 #
43 my $tqm = Thread::Queue::Multiplex->new(MaxPending => 20);
44 #
45 # register as a subscriber
46 #
47 $tqm->subscribe('myID');
48 #
49 # unregister as a subscriber
50 #
51 $tqm->unsubscribe();
52 #
53 # wait for $count subscribers to register
54 #
55 $tqm->wait_for_subscribers($count, $timeout);
56 #
57 # get the list of current subscribers ID's
58 #
59 my @subids = $tqm->get_subscribers();
60 #
61 # change the max pending limit
62 #
63 $tqm->set_max_pending($limit);
64 #
65 # enqueue elements, returning a unique queue ID
66 # (used in the client)
67 #
68 my $id = $tqm->publish("foo", "bar");
69 #
70 # publish elements, and wait for a response
71 # (used in the client)
72 #
73 my $resp = $tqm->publish_and_wait("foo", "bar");
74 #
75 # publish elements, and wait for a response
76 # until $timeout secs (used in the client)
77 #
78 my $resp = $tqm->publish_and_wait_until($timeout, "foo", "bar");
79 #
80 # publish elements at head of queue, returning a
81 # unique queue ID (used in the client)
82 #
83 my $id = $tqm->publish_urgent("foo", "bar");
84 #
85 # publish elements at head of queue and wait for response
86 #
87 my $resp = $tqm->publish_urgent_and_wait("foo", "bar");
88 #
89 # publish elements at head of queue and wait for
90 # response until $timeout secs
91 #
92 my $resp = $tqm->publish_urgent_and_wait_until($timeout, "foo", "bar");
93 #
94 # publish elements for simplex operation (no response)
95 # returning the queue object
96 #
97 $tqm->publish_simplex("foo", "bar");
98  
99 $tqm->publish_simplex_urgent("foo", "bar");
100 #
101 #########################################################
102 #
103 # subscribers use the existing TQD dequeue() methods
104 #
105 #######################################################
106 #
107 # modified versions of the TQD base enqueue methods
108 # to support directed messaging to a single subscriber
109 # or group of subscribers
110 #
111 #######################################################
112 #
113 # enqueue elements to a specific subscriber, returning
114 # a unique queue ID (used in the client)
115 #
116 my $id = $tqm->enqueue($subID, "foo", "bar");
117 #
118 # enqueue elements to 2 subscribers, and wait for a response
119 # (used in the client)
120 #
121 my $resp = $tqm->enqueue_and_wait([ $subID1, $subID2 ], "foo", "bar");
122 #
123 # enqueue elements, and wait for a response
124 # until $timeout secs (used in the client)
125 #
126 my $resp = $tqm->enqueue_and_wait_until($subID, $timeout, "foo", "bar");
127 #
128 # SEE Thread::Queue::Duplex for the various publisher enqueue()
129 # and wait() methods,
130 # and the subscriber dequeue() methods
131 #
132  
133 =head1 DESCRIPTION
134  
135 A subclass of L<Thread::Queue::Duplex> I<aka> B<TQD> which implements a
136 "publish and subscribe" communications model for threads. Subscribers
137 register with the queue, which registers either the provided subscriber ID,
138 or, if no ID is provided, 1 plus the TID of the subscriber's thread,
139 as a subscriber ID. As the publisher publishes
140 messages to the queue, each subscriber receives
141 a copy of the message. If the publication is B<not> simplex, the publisher
142 expects all subscribers to read and respond to the message; otherwise, the
143 publisher simply continues its processing. Thread::Queue::Multiplex
144 provides C<publish()> method counterparts for all the L<Thread::Queue::Duplex>
145 C<enqueue()> methods, e.g., C<publish_simplex(), publish_urgent(),
146 publish_and_wait(), publish_and_wait_until()>, etc.
147  
148 Subscribers receive and reply to messages using the existing TQD
149 dequeue() and respond() methods. In addition, modified versions of
150 the enqueue() methods are provided to publishers to permit directing
151 a message to a single subscriber, or subset of subscribers, by specifying
152 the scalar subscriber ID (for single subscriber messages), or
153 an arrayref of unique subscriber ID's (for multi-subscriber messages).
154  
155 C<Thread::Queue::Multiplex> subclass overrides some of the internal behavior
156 of L<Thread::Queue::Duplex> by
157  
158 =over 4
159  
160 =item *
161  
162 adding a shared hash to hold the list of unique subscriber ID's
163 (provided either explicitly with C<subscribe()>, or derived from
164 1 + L<threads>C<-E<gt>self()-E<gt>tid()> when the
165 subscriber C<subscribe()>s) mapped to a threads::shared
166 array to hold ID's of messages published to the subscriber.
167 (B<Note:> tid() + 1 is used in order to avoid an ID of zero
168 for the root thread).
169  
170 =item *
171  
172 adding a shared hash to hold the list of message ID's
173 mapped to a threads::shared array to containing
174 C<[message ID, flags, refcount, @params]>, where
175 C<flags> indicates the urgent and/or simplex status
176 of the request, and C<refcount> indicates the number
177 of subscribers assigned to the request. A special C<refcount>
178 value of -1 indicates that only the first subscriber to
179 retrieve/process the request should respond (to mimic the
180 behavior of L<Thread::Queueu::Duplex>), which is
181 specified by the publisher using any of the C<enqueue>
182 methods with a subscriber ID of -1.
183  
184 =item *
185  
186 adding a shared hash to hold the list of message ID's
187 mapped to a L<threads::shared> hash containing
188 a reference count of subscribers for the message,
189 and a map of subscriber IDs to their responses.
190 This "pending response" hash is used to accumulate
191 all subscriber responses; when the reference count of
192 a message is zero, the hash of responses is posted to
193 the final response message mapping hash.
194  
195 =item *
196  
197 adding a shared hash to hold the map of thread ID's to
198 subscriber ID's. B<Note:> Each thread can have only a single
199 subscriber.
200  
201 =item *
202  
203 changing the message mapping hash to map a unique message ID
204 to a hash of unique subscriber ID's, mapped to their response (if any),
205 i.e.,
206  
207 $msg_map = {
208 $msgid => {
209 $subID1 => $subID1_response,
210 $subID2 => $subID2_response,
211 etc.
212 }
213 }
214  
215 =item *
216  
217 when the publisher dequeues the response to a message, it receives
218 a copy of the subscriber mapping hash, and is responsible for iterating
219 over the hash to read each subscriber's results
220  
221 =back
222  
223 A normal processing sequence for Thread::Queue::Multiplex might be:
224  
225 #
226 # Thread A (the client):
227 #
228 ...marshal parameters for a coroutine...
229 my $id = $tqm->publish('function_name', \@paramlist);
230 my $results = $tqm->dequeue_response($id);
231 while (($subID, $subresult) = each %$results) {
232 ...process $results...
233 }
234 #
235 # Thread B (a subscriber):
236 #
237 while (1) {
238 my $call = $tqm->dequeue;
239 my ($id, $func, @params) = @$call;
240 $tqm->respond($id, $self->$func(@params));
241 }
242  
243 =head1 FUNCTIONS AND METHODS
244  
245 =over 4
246  
247 =item $tqm = B<Thread::Queue::Multiplex-E<gt>new>([MaxPending => $limit])
248  
249 Constructor. Creates a new empty queue.
250 If the C<MaxPending> value is a non-zero value, the number
251 of pending requests will be limited to C<$limit>, and any further
252 attempt to queue a request will block until the pending count
253 drops below C<$limit>. This limit may be applied or modified later
254 via the C<set_max_pending()> method (see below).
255  
256 =item B<subscribe( >I<[ $subID ]>B< )> I<aka> B<listen()>
257  
258 Subscribe to the queue. The listen() alias is provided for
259 compatibility with TQD apps. If C<$subID> is not provided, 1 plus
260 the current thread's TID is used as the subscriber ID.
261 Only a single subscriber per thread is permitted; undef will
262 be returned if the current thread already has a subscriber.
263  
264 =item B<unsubscribe()> I<aka> B<ignore()>
265  
266 Unsubscribe from the queue. The ignore() alias is provided for
267 compatibility with TQD apps. Note the subscriber for the current
268 thread is unsubscribed. I<Unsubscribing another thread is not
269 currently supported.>
270  
271 =item @subIDs = $tqm->B<get_subscribers()>
272  
273 Returns the current list of subscriber IDs.
274  
275 =item $msgID = $tqm->B<publish(@request)>
276  
277 L<enqueue>()s the C<@request> to all subscribers.
278  
279 =item $results = $tqm->B<publish_and_wait(@request)>
280  
281 Same as L<publish>, except that it waits for and returns
282 the response hash, rather than returning
283 immediately with the request ID.
284  
285 =item $results = $tqm->B<publish_and_wait_until($timeout, @request)>
286  
287 Same as L<publish>, except that it waits up to $timeout
288 seconds for all subscribers to respond, and returns the
289 response hash, rather
290 than returning immediately with the request ID. If some, but not all,
291 subscribers respond within the timeout, the responses are discarded.
292  
293 =item $msgID = $tqm->B<publish_urgent(@request)>
294  
295 Same as L<publish>, but adds the element to head of queue, rather
296 than tail.
297  
298 =item $results = $tqm->B<publish_urgent_and_wait(@request)>
299  
300 Same as L<publish_and_wait>, but adds the element to head of queue, rather
301 than tail.
302  
303 =item $results = $tqm->B<publish_urgent_and_wait_until($timeout, @request)>
304  
305 Same as L<publish_and_wait_until>, but adds the element to head of queue, rather
306 than tail.
307  
308 =item $msgID = $tqm->B<publish_simplex(@request)>
309  
310 Same as L<publish>, but does not allocate an identifier, nor
311 expect a response.
312  
313 =item $msgID = $tqm->B<publish_simplex_urgent(@request)>
314  
315 Same as L<publish_simplex>, but adds the element to head of queue,
316 rather than tail.
317  
318 =item $count = $tqm->B<pending()>
319  
320 Returns the number of items still in the queue.
321 B<Note> that, for subscribers, the returned value
322 is the number of requests published to the individual subscriber,
323 which may be less than the total number of pending requests,
324 due to directed C<enqueue> requests. Also, for subscribers,
325 the number may include requests which have been cancelled,
326 but not yet processed/discarded by the subscriber.
327  
328 =back
329  
330 The following TQD methods are overloaded by TQM to support
331 directed requests by adding either a single scalar subscriber
332 ID, or an arrayref of multiple subscriber IDs, as the first
333 parameter:
334  
335 =over 4
336  
337 =item $msgID = $tqm->enqueue( $subID, @request)
338  
339 =item $msgID = $tqm->enqueue( [ @subIDs ], @request)
340  
341 =item $msgID = $tqm->enqueue_simplex( $subID, @request)
342  
343 =item $msgID = $tqm->enqueue_simplex( [ @subIDs ], @request)
344  
345 =item $msgID = $tqm->enqueue_urgent( $subID, @request)
346  
347 =item $msgID = $tqm->enqueue_urgent( [ @subIDs ], @request)
348  
349 =item $msgID = $tqm->enqueue_simplex_urgent( $subID, @request)
350  
351 =item $msgID = $tqm->enqueue_simplex_urgent( [ @subIDs ], @request)
352  
353 =item $result = $tqm->enqueue_and_wait( $subID, @request)
354  
355 =item $result = $tqm->enqueue_and_wait( [ @subIDs ], @request)
356  
357 =item $result = $tqm->enqueue_urgent_and_wait( $subID, @request)
358  
359 =item $result = $tqm->enqueue_urgent_and_wait( [ @subIDs ], @request)
360  
361 =item $result = $tqm->enqueue_and_wait_until( $subID, $timeout, @request)
362  
363 =item $result = $tqm->enqueue_and_wait_until( [ @subIDs ], $timeout, @request)
364  
365 =item $result = $tqm->enqueue_urgent_and_wait_until( $subID, $timeout, @request)
366  
367 =item $result = $tqm->enqueue_urgent_and_wait_until( [ @subIDs ], $timeout, @request)
368  
369 =back
370  
371 =head1 CAVEATS
372  
373 If any subscriber thread dies, then the publisher may hang
374 on any of the blocking publish calls, or the wait()/dequeue_response().
375 A future update may support occasional scans and forced
376 unsubscribe() for dead threads.
377  
378 =head1 SEE ALSO
379  
380 L<Thread::Queue::Duplex>
381 L<Thread::Queue::Queueable>,
382 L<threads>
383 L<threads::shared>
384 L<Thread::Queue>
385  
386 =head1 AUTHOR, COPYRIGHT, & LICENSE
387  
388 Dean Arnold, Presicient Corp. L<darnold@presicient.com>
389  
390 Copyright(C) 2006, Presicient Corp., USA
391  
392 Licensed under the Academic Free License version 2.1, as specified in the
393 License.txt file included in this software package, or at OpenSource.org
394 L<http://www.opensource.org/licenses/afl-2.1.php>.
395  
396 =cut
397  
398 #
399 # global semaphore used for class-level wait()
400 # notification
401 #
402 use Thread::Queue::Duplex;
403 use Thread::Queue::Duplex qw(:tqd_codes $tqd_global_lock);
404 use base qw(Thread::Queue::Duplex);
405 #
406 # import the following member names from TQD:
407 #
408 #use constant TQD_Q => 0;
409 #use constant TQD_MAP => 1;
410 #use constant TQD_IDGEN => 2;
411 #use constant TQD_LISTENERS => 3;
412 #use constant TQD_REQUIRE_LISTENER => 4;
413 #use constant TQD_MAX_PENDING => 5;
414 #use constant TQD_URGENT_COUNT => 6;
415 #use constant TQD_MARKS => 7;
416 #
417 # then add our own
418 #
419 use constant TQM_SUBSCRIBERS => 8;
420 use constant TQM_SUB_MAP => 9;
421 use constant TQM_PENDING_MAP => 10;
422 use constant TQM_SUB_ID_MAP => 11;
423 #
424 # flags for special msgs
425 #
426 use constant TQM_URGENT => 1;
427 use constant TQM_SIMPLEX => 2;
428 use constant TQM_URGENT_SIMPLEX => 3;
429 #
430 # when used for subid, indicates only the
431 # first sub to see it should process the msg
432 # (ie reverts to TQD behavior)
433 #
434 use constant TQM_FIRST_ONLY => -1;
435 #################################################
436 #
437 # The following methods are inherited from TQD:
438 # _get_id()
439 # _filter_nq()
440 # wait_for_listener()
441 # set_max_pending()
442 # wait()
443 # dequeue_response()
444 # ready()
445 # available()
446 # wait_until()
447 # wait_any()
448 # wait_any_until()
449 # wait_all()
450 # wait_all_until()
451 # mark()
452 # unmark()
453 # get_mark()
454 # marked()
455 # _tqd_wait()
456 # TQQ curse()/redeem()
457 #
458 ##################################################
459 #################################################
460 #
461 # !!!NOTE!!!NOTE!!!NOTE!!!NOTE!!!NOTE!!!NOTE!!!NOTE
462 #
463 # always retain this lock order:
464 # TQD_Q before TQM_PENDING_MAP
465 # TQM_PENDING_MAP before TQD_MAP
466 # TQM_MAP before TQD_MARKS
467 #
468 #################################################
469  
470 sub new {
471 my $class = shift;
472  
473 my $obj = $class->SUPER::new(@_);
474 return undef unless $obj;
475 #
476 # map of subids to their msgid queues
477 #
478 my %subscribers : shared = ();
479 #
480 # map of msgids to their pending msg info
481 #
482 my %pendingmsgs : shared = ();
483 #
484 # map of msgids to their pending response info
485 #
486 my %pendingresps : shared = ();
487 #
488 # map of subscriber TIDs to their sub ID
489 #
490 my %subids : shared = ();
491  
492 $obj->[TQM_SUBSCRIBERS] = \%subscribers;
493 $obj->[TQM_SUB_MAP] = \%pendingmsgs;
494 $obj->[TQM_PENDING_MAP] = \%pendingresps;
495 $obj->[TQM_SUB_ID_MAP] = \%subids;
496 return $obj;
497 }
498  
499 sub subscribe {
500 my $obj = shift;
501 my $tid = threads->self()->tid() + 1;
502 my $id = shift || $tid;
503 lock(${$obj->[TQD_LISTENERS]});
504 #
505 # we only permit a single subscriber per thread
506 #
507 $@ = 'Thread $tid already subscribed as ' .
508 $obj->[TQM_SUB_ID_MAP]{$tid},
509 return undef
510 if $obj->[TQM_SUB_ID_MAP]{$tid};
511  
512 ${$obj->[TQD_LISTENERS]}++;
513 my @pending_msgs : shared = ();
514 $obj->[TQM_SUBSCRIBERS]{$id} = \@pending_msgs;
515 $obj->[TQM_SUB_ID_MAP]{$tid} = $id;
516 cond_broadcast(${$obj->[TQD_LISTENERS]});
517 return $obj;
518 }
519  
520 sub unsubscribe {
521 my $obj = shift;
522 my $id = threads->self()->tid() + 1;
523 my $pending;
524 {
525 lock(${$obj->[TQD_LISTENERS]});
526 $@ = "No subscriber in thread $id.",
527 return undef
528 unless $obj->[TQM_SUB_ID_MAP]{$id};
529 $id = delete $obj->[TQM_SUB_ID_MAP]{$id};
530 $pending = delete $obj->[TQM_SUBSCRIBERS]{$id};
531 ${$obj->[TQD_LISTENERS]}--
532 if ${$obj->[TQD_LISTENERS]};
533 }
534 return $obj unless scalar @$pending;
535  
536 my @completed = ();
537 #
538 # walk pending requests and remove any reference to ourselves,
539 # possibly signalling request completion if we're the only/last
540 # subscriber
541 # Note we leave pending responses intact
542 #
543 {
544 lock(@{$obj->[TQD_Q]});
545 foreach (@$pending) {
546 #
547 # need to be careful here due to inconsistent deref behavior of
548 # threads::shared
549 #
550 if ($obj->[TQM_SUB_MAP]{$_}) {
551 my $entry = $obj->[TQM_SUB_MAP]{$_};
552 if ($entry->{_refcnt} && ($entry->{_refcnt} != TQM_FIRST_ONLY)) {
553 #
554 # what should we do about FIRST_ONLY here ?
555 # if we're the only sub, then the publisher may get
556 # hung...for now, we'll ignore them
557 #
558 $entry->{_refcnt}--;
559 push @completed, $_
560 unless $entry->{_refcnt};
561 }
562 }
563 }
564 }
565 #
566 # we postpone posting completions so we don't constantly
567 # lock/unlock ..and possibly deadlock...; this way we
568 # can just lock, post all, unlock
569 #
570 $obj->_post_complete(@completed)
571 if scalar @completed;
572  
573 return $obj;
574 }
575 #
576 # override listen/ignore to mimic subscribe/unsubscribe
577 #
578 sub listen {
579 return subscribe(@_);
580 }
581  
582 sub ignore {
583 return unsubscribe(@_);
584 }
585  
586 sub get_subscribers {
587 my $obj = shift;
588 lock(${$obj->[TQD_LISTENERS]});
589 return keys %{$obj->[TQM_SUBSCRIBERS]};
590 }
591 #
592 # wait until we've got subscribers
593 #
594 sub wait_for_subscribers {
595 my ($obj, $count, $timeout) = @_;
596 my $listeners = $obj->[TQD_LISTENERS];
597 lock($$listeners);
598  
599 return undef
600 if ($timeout && ($timeout < 0));
601  
602 if ($timeout) {
603 $timeout += time();
604 cond_timedwait($$listeners, $timeout)
605 while ($$listeners != $count) && ($timeout > time());
606  
607 return ($$listeners eq $count) ? $obj : undef;
608 }
609  
610 cond_wait($$listeners)
611 while ($$listeners != $count);
612 return ($$listeners == $count) ? $obj : undef;
613 }
614 #
615 # override lock & load to include subid list
616 #
617 sub _lock_load {
618 my $obj = shift;
619 my $flags = shift || 0;
620 my $subs = shift;
621 #
622 # create shared array of params here, leaving
623 # the open spot for the subids list
624 #
625 my $msgid = $obj->_get_id; # always assign ID, even for simplex
626 #
627 # NOTE: we trick _filter_nq into opening up a couple extra
628 # slots for us, which we later fill with an Underdog
629 # Super Energy Pill, namely, the simplex flag and the refcnt
630 #
631 my $params = Thread::Queue::Duplex::_filter_nq($msgid, undef, @_);
632 $params->[1] = $flags;
633 #
634 # Note that sequence is important here;
635 # a sub may unsubscribe after we've
636 # published to it, but before msg delivery...but
637 # the unsubscribe process will purge the sub
638 # from any pending msgs. We don't publish
639 # to subs that aren't subscribed; since we have
640 # to cond_wait until the queue length is under the max,
641 # we don't do subs assignment until then (in case
642 # some subs unsubscribe while we're cond_waiting)
643 #
644 my $q = $obj->[TQD_Q];
645 lock(@$q);
646 #
647 # check current length if we have a limit
648 #
649 while (${$obj->[TQD_MAX_PENDING]} &&
650 (${$obj->[TQD_MAX_PENDING]} <= scalar keys %{$obj->[TQM_SUB_MAP]})) {
651 # print "pending before: ", scalar @$q, "\n";
652 cond_wait(@$q);
653 # print "pending after: ", scalar @$q, "\n";
654 }
655  
656 my $firstonly = (defined($subs) && (! ref $subs) && ($subs == TQM_FIRST_ONLY));
657 $subs = (defined($subs) && (! $firstonly)) ?
658 [ $subs ] :
659 [ keys %{$obj->[TQM_SUBSCRIBERS]} ]
660 unless defined($subs) && (ref $subs);
661  
662 $params->[2] = $firstonly ? TQM_FIRST_ONLY : scalar @$subs;
663 $obj->[TQM_SUB_MAP]{$msgid} = $params;
664 unless ($params->[1] & TQM_SIMPLEX) {
665 #
666 # if we need a response, post the prelim
667 #
668 my %pending : shared = (_refcnt => $params->[2]);
669 lock(%{$obj->[TQM_PENDING_MAP]});
670 $obj->[TQM_PENDING_MAP]{$msgid} = \%pending;
671 }
672 #
673 # now post the msgid to every assigned sub's queue
674 # at present, we'll use the TQD_Q lock to lock these as well
675 #
676 foreach (@$subs) {
677 my $s = $obj->[TQM_SUBSCRIBERS]{$_};
678 ($flags & TQM_URGENT) ?
679 unshift @$s, $msgid :
680 push @$s, $msgid;
681 }
682 cond_broadcast @$q;
683 return $msgid;
684 }
685  
686  
687 ###########################
688 #
689 # publish methods:
690 # Note the parlor trick: we just alias to the
691 # enqueue() methods, but with a funky
692 # signature to indicate that all subs
693 # should be queued
694 # FYI: subscribers registering after we publish,
695 # but before the msg is fully consumed, won't get
696 # the message
697 #
698 sub publish {
699 return enqueue(undef, @_);
700 }
701  
702 sub publish_urgent {
703 return enqueue_urgent(undef, @_);
704 }
705 #
706 # blocking versions of publish()
707 #
708 sub publish_and_wait {
709 return enqueue_and_wait(undef, @_);
710 }
711  
712 sub publish_and_wait_until {
713 return enqueue_and_wait_until(undef, @_);
714 }
715  
716 sub publish_urgent_and_wait {
717 return enqueue_urgent_and_wait(undef, @_);
718 }
719  
720 sub publish_urgent_and_wait_until {
721 return enqueue_urgent_and_wait_until(undef, @_);
722 }
723 #
724 # Simplex versions
725 #
726 sub publish_simplex {
727 return enqueue_simplex(undef, @_);
728 }
729  
730 sub publish_simplex_urgent {
731 return enqueue_simplex_urgent(undef, @_);
732 }
733 #
734 # override of base enqueue methods
735 #
736 sub enqueue {
737 my $obj = shift;
738 my $subs = shift;
739 #
740 # check if its a publish...
741 #
742 ($obj, $subs) = ($subs, undef)
743 unless defined($obj);
744  
745 return undef
746 if ($obj->[TQD_REQUIRE_LISTENER] &&
747 (! ${$obj->[TQD_LISTENERS]}));
748 my $id = _lock_load($obj, undef, $subs, @_);
749 lock($tqd_global_lock);
750 cond_broadcast($tqd_global_lock);
751 return $id;
752 }
753  
754 sub enqueue_urgent {
755 my $obj = shift;
756 my $subs = shift;
757 #
758 # check if its a publish...
759 #
760 ($obj, $subs) = ($subs, undef)
761 unless defined($obj);
762  
763 return undef
764 if ($obj->[TQD_REQUIRE_LISTENER] &&
765 (! ${$obj->[TQD_LISTENERS]}));
766 my $id = _lock_load($obj, TQM_URGENT, $subs, @_);
767  
768 lock($tqd_global_lock);
769 cond_broadcast($tqd_global_lock);
770 return $id;
771 }
772 #
773 # blocking versions of enqueue()
774 #
775 sub enqueue_and_wait {
776 my $obj = shift;
777 #
778 # check if its a publish...
779 #
780 $obj = shift,
781 unshift @_, undef
782 unless defined($obj);
783  
784 my $id = $obj->enqueue(@_);
785 return defined($id) ? $obj->wait($id) : undef;
786 }
787  
788 sub enqueue_and_wait_until {
789 my $obj = shift;
790 my $subs = shift;
791 my $timeout = shift;
792 #
793 # check if its a publish...
794 #
795 ($obj, $subs) = ($subs, undef)
796 unless defined($obj);
797  
798 my $id = $obj->enqueue($subs, @_);
799 return defined($id) ? $obj->wait_until($id, $timeout) : undef;
800 }
801  
802 sub enqueue_urgent_and_wait {
803 my $obj = shift;
804 #
805 # check if its a publish...
806 #
807 $obj = shift,
808 unshift @_, undef
809 unless defined($obj);
810  
811 my $id = $obj->enqueue_urgent(@_);
812 return defined($id) ? $obj->wait($id) : undef;
813 }
814  
815 sub enqueue_urgent_and_wait_until {
816 my $obj = shift;
817 my $subs = shift;
818 my $timeout = shift;
819 #
820 # check if its a publish...
821 #
822 ($obj, $subs) = ($subs, undef)
823 unless defined($obj);
824  
825 my $id = $obj->enqueue_urgent($subs, @_);
826 return defined($id) ? $obj->wait_until($id, $timeout) : undef;
827 }
828 #
829 # Simplex versions
830 #
831 sub enqueue_simplex {
832 my $obj = shift;
833 my $subs = shift;
834 #
835 # check if its a publish...
836 #
837 ($obj, $subs) = ($subs, undef)
838 unless defined($obj);
839  
840 return undef
841 if ($obj->[TQD_REQUIRE_LISTENER] &&
842 (! ${$obj->[TQD_LISTENERS]}));
843  
844 _lock_load($obj, TQM_SIMPLEX, $subs, @_);
845  
846 lock($tqd_global_lock);
847 cond_broadcast($tqd_global_lock);
848 return $obj;
849 }
850  
851 sub enqueue_simplex_urgent {
852 my $obj = shift;
853 my $subs = shift;
854 #
855 # check if its a publish...
856 #
857 ($obj, $subs) = ($subs, undef)
858 unless defined($obj);
859  
860 return undef
861 if ($obj->[TQD_REQUIRE_LISTENER] &&
862 (! ${$obj->[TQD_LISTENERS]}));
863  
864 _lock_load($obj, TQM_URGENT_SIMPLEX, $subs, @_);
865  
866 lock($tqd_global_lock);
867 cond_broadcast($tqd_global_lock);
868 return $obj;
869 }
870  
871 #
872 # recover original param list, including reblessing Queueables
873 # NOTE: we need to maintain the list until all the subs have
874 # consumed it
875 #
876 sub _filter_dq {
877 my $result = shift;
878 #
879 # keep ID; collapse the rest
880 #
881 my @results = (($result->[1] & TQM_SIMPLEX) ? undef : $result->[0]);
882 my $class;
883 my $i = 3;
884  
885 $class = $result->[$i++],
886 push (@results,
887 $class ?
888 ${class}->onDequeue($result->[$i++]) :
889 $result->[$i++])
890 while ($i < scalar @$result);
891  
892 return \@results;
893 }
894 #
895 # common method for getting the request out of the queue
896 #
897 sub _get_request {
898 my ($obj, $msgid, $need_urgent) = @_;
899 #
900 # cancelled request (ie map entry has been deleted) ?
901 #
902 return undef
903 unless exists $obj->[TQM_SUB_MAP]{$msgid};
904  
905 my $request = $obj->[TQM_SUB_MAP]{$msgid};
906 return undef
907 if ($need_urgent && (!($request->[1] & TQM_URGENT)));
908 $request->[2]--
909 unless ($request->[2] == TQM_FIRST_ONLY);
910 delete $obj->[TQM_SUB_MAP]{$msgid}
911 if ($request->[2] <= 0);
912 return $request;
913 }
914  
915 sub dequeue {
916 my $obj = shift;
917 my $request;
918 my $id = $obj->[TQM_SUB_ID_MAP]{threads->self()->tid() + 1};
919 $@ = 'No subscriber for thread ' . threads->self()->tid(),
920 return undef
921 unless $id;
922  
923 my $q = $obj->[TQD_Q];
924 while (1) {
925  
926 lock(@$q);
927 my $s = $obj->[TQM_SUBSCRIBERS]{$id};
928  
929 cond_wait @$q
930 while (! scalar @$s);
931  
932 # print $id, " dequeue\n";
933  
934 $request = $obj->_get_request(shift @$s);
935 next unless $request;
936 #
937 # signal any waiters
938 #
939 cond_broadcast @$q;
940 last;
941 }
942 return _filter_dq($request);
943 }
944  
945 sub dequeue_until {
946 my ($obj, $timeout) = @_;
947  
948 return undef
949 unless $timeout && ($timeout > 0);
950  
951 $timeout += time();
952 my $request;
953 my $id = $obj->[TQM_SUB_ID_MAP]{threads->self()->tid() + 1};
954 $@ = 'No subscriber for thread ' . threads->self()->tid(),
955 return undef
956 unless $id;
957  
958 my $q = $obj->[TQD_Q];
959 while (1)
960 {
961 lock(@$q);
962 my $s = $obj->[TQM_SUBSCRIBERS]{$id};
963  
964 cond_timedwait(@$q, $timeout)
965 while (! scalar @$s) && ($timeout > time());
966 #
967 # if none, then we must've timed out
968 #
969 return undef
970 unless scalar @$s;
971  
972 # print $id, " dequeue_until\n";
973  
974 $request = $obj->_get_request(shift @$s);
975 next unless $request;
976 #
977 # signal any waiters
978 #
979 cond_broadcast @$q;
980 last;
981 }
982 return _filter_dq($request);
983 }
984  
985 sub dequeue_nb {
986 my $obj = shift;
987 my $request;
988 my $id = $obj->[TQM_SUB_ID_MAP]{threads->self()->tid() + 1};
989 $@ = 'No subscriber for thread ' . threads->self()->tid(),
990 return undef
991 unless $id;
992 my $q = $obj->[TQD_Q];
993 while (1)
994 {
995 lock(@$q);
996 my $s = $obj->[TQM_SUBSCRIBERS]{$id};
997 return undef
998 unless scalar @$s;
999 # print $id, " dequeue_nb\n";
1000 #
1001 $request = $obj->_get_request(shift @$s);
1002 return undef unless $request;
1003 #
1004 # signal any waiters
1005 #
1006 cond_broadcast @$q;
1007 last;
1008 }
1009 return _filter_dq($request);
1010 }
1011  
1012 sub dequeue_urgent {
1013 my $obj = shift;
1014 my $request;
1015 my $id = $obj->[TQM_SUB_ID_MAP]{threads->self()->tid() + 1};
1016 $@ = 'No subscriber for thread ' . threads->self()->tid(),
1017 return undef
1018 unless $id;
1019 my $q = $obj->[TQD_Q];
1020 while (1)
1021 {
1022 lock(@$q);
1023 my $s = $obj->[TQM_SUBSCRIBERS]{$id};
1024 return undef
1025 unless scalar @$s;
1026  
1027 $request = $obj->_get_request(shift @$s, 1);
1028 return undef unless $request;
1029 #
1030 # signal any waiters
1031 #
1032 cond_broadcast @$q;
1033 last;
1034 }
1035 return _filter_dq($request);
1036 }
1037  
1038 sub pending {
1039 my $obj = shift;
1040 #
1041 # returned value depends on context: if its a
1042 # sub, return its queue; else return the
1043 # number of keys in the request map
1044 #
1045 my $id = $obj->[TQM_SUB_ID_MAP]{threads->self()->tid() + 1};
1046 lock(@{$obj->[TQD_Q]});
1047 return scalar keys %{$obj->[TQM_SUB_MAP]}
1048 unless defined($id) && exists $obj->[TQM_SUBSCRIBERS]{$id};
1049 #
1050 # Texas 2 step to avoid issues w/ threads::shared
1051 #
1052 my $q = $obj->[TQM_SUBSCRIBERS]{$id};
1053 return scalar @$q;
1054 }
1055  
1056 #
1057 # common function for building response list
1058 #
1059 sub _create_resp {
1060 my @params : shared = ((undef) x (scalar @_ << 1));
1061 #
1062 # marshall params, checking for Queueable objects
1063 #
1064 my $i = 0;
1065 foreach (@_) {
1066 if (ref $_ &&
1067 (ref $_ ne 'ARRAY') &&
1068 (ref $_ ne 'HASH') &&
1069 (ref $_ ne 'SCALAR') &&
1070 $_->isa('Thread::Queue::Queueable')) {
1071 #
1072 # invoke onEnqueue method
1073 #
1074 $params[$i] = ref $_;
1075 $params[$i+1] = $_->onEnqueue();
1076 }
1077 else {
1078 @params[$i..$i+1] = (undef, $_);
1079 }
1080 $i += 2;
1081 }
1082 return \@params;
1083 }
1084  
1085 sub respond {
1086 my $obj = shift;
1087 my $msgid = shift;
1088 my $id = $obj->[TQM_SUB_ID_MAP]{threads->self()->tid() + 1};
1089 $@ = 'No subscriber for thread ' . threads->self()->tid(),
1090 return undef
1091 unless $id;
1092 #
1093 # silently ignore response to a simplex request
1094 #
1095 return $obj unless defined($msgid);
1096  
1097 my $result = _create_resp(@_);
1098 my $pending;
1099 {
1100 lock(%{$obj->[TQM_PENDING_MAP]});
1101 #
1102 # check if its been canceled
1103 #
1104 _cancel_resp({ $id => $result }),
1105 return $obj
1106 unless exists $obj->[TQM_PENDING_MAP]{$msgid};
1107 $pending = $obj->[TQM_PENDING_MAP]{$msgid};
1108 #
1109 # else post result, update refcount, and if done,
1110 # post completion; make sure we use same lock order
1111 # everywhere
1112 #
1113 $pending->{$id} = $result;
1114 $pending->{_refcnt}--
1115 if $pending->{_refcnt} && ($pending->{_refcnt} > 0);
1116  
1117 if ($pending->{_refcnt} <= 0) {
1118 delete $pending->{_refcnt};
1119 lock(%{$obj->[TQD_MAP]});
1120 $obj->[TQD_MAP]{$msgid} = delete $obj->[TQM_PENDING_MAP]{$msgid};
1121 cond_broadcast %{$obj->[TQD_MAP]};
1122 #
1123 # order is important; we always lock MAP before MARK
1124 #
1125 lock(%{$obj->[TQD_MARKS]});
1126 delete $obj->[TQD_MARKS]{$msgid};
1127 }
1128 }
1129  
1130 lock($tqd_global_lock);
1131 cond_broadcast($tqd_global_lock);
1132  
1133 return $obj;
1134 }
1135 #
1136 # common function for filtering response list
1137 #
1138 sub _filter_resp {
1139 my ($obj, $result) = @_;
1140 #
1141 # collapse the response elements
1142 #
1143 delete $result->{_refcnt};
1144 my %results = ();
1145 my $class;
1146 my $persub;
1147 my $subresp;
1148 foreach (keys %$result) {
1149 $results{$_} = $subresp = [];
1150 $persub = $result->{$_};
1151 $class = shift @$persub,
1152 push (@$subresp,
1153 $class ?
1154 ${class}->onDequeue(shift @$persub) :
1155 shift @$persub)
1156 while (@$persub);
1157 }
1158 return \%results;
1159 }
1160 #
1161 # called to post completion when a sub unsubscribes
1162 #
1163 sub _post_complete {
1164 my $obj = shift;
1165  
1166 my $count = 0;
1167 {
1168 #
1169 # note: lock order is important!
1170 #
1171 lock(%{$obj->[TQM_PENDING_MAP]});
1172 lock(%{$obj->[TQD_MAP]});
1173 lock(%{$obj->[TQD_MARKS]});
1174 foreach (@_) {
1175 delete $obj->[TQD_MARKS]{$_};
1176 #
1177 # check if its been canceled
1178 #
1179 next
1180 unless exists $obj->[TQM_PENDING_MAP]{$_};
1181 #
1182 # Texas 2 step to avoid threads::shared misbehavior
1183 #
1184 my $pending = delete $obj->[TQM_PENDING_MAP]{$_};
1185 delete $pending->{_refcnt};
1186 $obj->[TQD_MAP]{$_} = $pending;
1187 $count++;
1188 }
1189  
1190 cond_broadcast %{$obj->[TQD_MAP]}
1191 if $count;
1192 }
1193  
1194 if ($count) {
1195 lock($tqd_global_lock);
1196 cond_broadcast($tqd_global_lock);
1197 }
1198 return $obj;
1199 }
1200  
1201 sub _cancel_resp {
1202 my $resp = shift;
1203 #
1204 # collapse the response elements,
1205 # and call onCancel to any that are Queueables
1206 #
1207 my $class;
1208 delete $resp->{_refcnt};
1209 foreach (values %$resp) {
1210 $class = shift @$_,
1211 $class ?
1212 ${class}->onCancel(shift @$_) :
1213 shift @$_
1214 while (@$_);
1215 }
1216 return 1;
1217 }
1218  
1219 sub cancel {
1220 my $obj = shift;
1221 #
1222 # *always* lock in this order to avoid deadlock
1223 #
1224 lock(@{$obj->[TQD_Q]});
1225 lock(%{$obj->[TQM_PENDING_MAP]});
1226 lock(%{$obj->[TQD_MAP]});
1227 lock(%{$obj->[TQD_MARKS]});
1228 foreach (@_) {
1229 delete $obj->[TQD_MARKS]{$_};
1230 #
1231 # delete submap entry,
1232 # and purge any pending responses
1233 #
1234 delete $obj->[TQM_SUB_MAP]{$_}
1235 if exists $obj->[TQM_SUB_MAP]{$_};
1236 #
1237 # if already responded to, call onCancel for any Queueuables
1238 #
1239 my $resp =
1240 (exists $obj->[TQM_PENDING_MAP]{$_}) ?
1241 delete $obj->[TQM_PENDING_MAP]{$_} :
1242 (exists $obj->[TQD_MAP]{$_}) ?
1243 delete $obj->[TQD_MAP]{$_} :
1244 undef;
1245 _cancel_resp($resp) if $resp;
1246 }
1247 return $obj;
1248 }
1249  
1250 sub cancel_all {
1251 my $obj = shift;
1252 #
1253 # when we lock both, *always* lock in this order to avoid
1254 # deadlock
1255 #
1256 lock(@{$obj->[TQD_Q]});
1257 lock(%{$obj->[TQM_PENDING_MAP]});
1258 lock(%{$obj->[TQD_MAP]});
1259 lock(%{$obj->[TQD_MARKS]});
1260 #
1261 # first cancel all pending responses
1262 #
1263 _cancel_resp(delete $obj->[TQM_PENDING_MAP]{$_})
1264 foreach (keys %{$obj->[TQM_PENDING_MAP]});
1265  
1266 _cancel_resp(delete $obj->[TQD_MAP]{$_})
1267 foreach (keys %{$obj->[TQD_MAP]});
1268 #
1269 # then cancel all the pending requests by
1270 # setting their IDs to -1
1271 #
1272 delete $obj->[TQD_MARKS]{$_},
1273 delete $obj->[TQM_SUB_MAP]{$_}
1274 foreach (keys %{$obj->[TQM_SUB_MAP]});
1275 #
1276 # how will we cancel inprogress requests ??
1277 # need a map value, or alternate map...
1278 #
1279 return $obj;
1280 }
1281  
1282 1;