-
Notifications
You must be signed in to change notification settings - Fork 86
/
multitask.py
executable file
·1287 lines (975 loc) · 40.4 KB
/
multitask.py
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
################################################################################
#
# Copyright (c) 2007 Christopher J. Stawarz
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
################################################################################
"""
Cooperative multitasking and asynchronous I/O using generators
multitask allows Python programs to use generators (a.k.a. coroutines)
to perform cooperative multitasking and asynchronous I/O.
Applications written using multitask consist of a set of cooperating
tasks that yield to a shared task manager whenever they perform a
(potentially) blocking operation, such as I/O on a socket or getting
data from a queue. The task manager temporarily suspends the task
(allowing other tasks to run in the meantime) and then restarts it
when the blocking operation is complete. Such an approach is suitable
for applications that would otherwise have to use select() and/or
multiple threads to achieve concurrency.
The functions and classes in the multitask module allow tasks to yield
for I/O operations on sockets and file descriptors, adding/removing
data to/from queues, or sleeping for a specified interval. When
yielding, a task can also specify a timeout. If the operation for
which the task yielded has not completed after the given number of
seconds, the task is restarted, and a Timeout exception is raised at
the point of yielding.
As a very simple example, here's how one could use multitask to allow
two unrelated tasks to run concurrently:
>>> def printer(message):
... while True:
... print message
... yield
...
>>> multitask.add(printer('hello'))
>>> multitask.add(printer('goodbye'))
>>> multitask.run()
hello
goodbye
hello
goodbye
hello
goodbye
[and so on ...]
For a more useful example, here's how one could implement a
multitasking server that can handle multiple concurrent client
connections:
def listener(sock):
while True:
conn, address = (yield multitask.accept(sock))
multitask.add(client_handler(conn))
def client_handler(sock):
while True:
request = (yield multitask.recv(sock, 1024))
if not request:
break
response = handle_request(request)
yield multitask.send(sock, response)
multitask.add(listener(sock))
multitask.run()
Tasks can also yield other tasks, which allows for composition of
tasks and reuse of existing multitasking code. A child task runs
until it either completes or raises an exception. To return output to
its parent, a child task raises StopIteration, passing the output
value(s) to the StopIteration constructor. An unhandled exception
raised within a child task is propagated to its parent. For example:
>>> def parent():
... print (yield return_none())
... print (yield return_one())
... print (yield return_many())
... try:
... yield raise_exception()
... except Exception, e:
... print 'caught exception: %s' % e
...
>>> def return_none():
... yield
... # do nothing
... # or return
... # or raise StopIteration
... # or raise StopIteration(None)
...
>>> def return_one():
... yield
... raise StopIteration(1)
...
>>> def return_many():
... yield
... raise StopIteration(2, 3) # or raise StopIteration((2, 3))
...
>>> def raise_exception():
... yield
... raise RuntimeError('foo')
...
>>> multitask.add(parent())
>>> multitask.run()
None
1
(2, 3)
caught exception: foo
"""
import collections
import errno
from functools import partial
import heapq
import os
import select
import sys
import time
import types
__author__ = 'Christopher Stawarz <[email protected]>'
__version__ = '0.2.0'
# __revision__ = int('$Revision$'.split()[1])
################################################################################
#
# Timeout exception type
#
################################################################################
class Timeout(Exception):
'Raised in a yielding task when an operation times out'
pass
################################################################################
#
# _ChildTask class
#
################################################################################
class _ChildTask(object):
def __init__(self, parent, task):
self.parent = parent
self.task = task
def send(self, value):
return self.task.send(value)
def throw(self, type, value=None, traceback=None):
return self.task.throw(type, value, traceback)
################################################################################
#
# YieldCondition class
#
################################################################################
class YieldCondition(object):
"""
Base class for objects that are yielded by a task to the task
manager and specify the condition(s) under which the task should
be restarted. Only subclasses of this class are useful to
application code.
"""
def __init__(self, timeout=None):
"""
If timeout is None, the task will be suspended indefinitely
until the condition is met. Otherwise, if the condition is
not met within timeout seconds, a Timeout exception will be
raised in the yielding task.
"""
self.task = None
self.handle_expiration = None
if timeout is None:
self.expiration = None
else:
self.expiration = time.time() + float(timeout)
def _expires(self):
return (self.expiration is not None)
################################################################################
#
# _SleepDelay class and related functions
#
################################################################################
class _SleepDelay(YieldCondition):
def __init__(self, seconds):
seconds = float(seconds)
if seconds <= 0.0:
raise ValueError("'seconds' must be greater than 0")
super(_SleepDelay, self).__init__(seconds)
def sleep(seconds):
"""
A task that yields the result of this function will be resumed
after the specified number of seconds have elapsed. For example:
while too_early():
yield sleep(5) # Sleep for five seconds
do_something() # Done sleeping; get back to work
"""
return _SleepDelay(seconds)
################################################################################
#
# FDReady class and related functions
#
################################################################################
class FDReady(YieldCondition):
"""
A task that yields an instance of this class will be suspended
until a specified file descriptor is ready for I/O.
"""
def __init__(self, fd, read=False, write=False, exc=False, timeout=None):
"""
Resume the yielding task when fd is ready for reading,
writing, and/or "exceptional" condition handling. fd can be
any object accepted by select.select() (meaning an integer or
an object with a fileno() method that returns an integer).
Any exception raised by select() due to fd will be re-raised
in the yielding task.
If timeout is not None, a Timeout exception will be raised in
the yielding task if fd is not ready after timeout seconds
have elapsed.
"""
super(FDReady, self).__init__(timeout)
self.fd = (fd if _is_file_descriptor(fd) else fd.fileno())
if not (read or write or exc):
raise ValueError("'read', 'write', and 'exc' cannot all be false")
self.read = read
self.write = write
self.exc = exc
def fileno(self):
'Return the file descriptor on which the yielding task is waiting'
return self.fd
def _add_to_fdsets(self, read_fds, write_fds, exc_fds):
for add, fdset in ((self.read, read_fds),
(self.write, write_fds),
(self.exc, exc_fds)):
if add:
fdset.add(self)
def _remove_from_fdsets(self, read_fds, write_fds, exc_fds):
for fdset in (read_fds, write_fds, exc_fds):
fdset.discard(self)
def _is_file_descriptor(fd):
return isinstance(fd, (int, long))
def readable(fd, timeout=None):
"""
A task that yields the result of this function will be resumed
when fd is readable. If timeout is not None, a Timeout exception
will be raised in the yielding task if fd is not readable after
timeout seconds have elapsed. For example:
try:
yield readable(sock, timeout=5)
data = sock.recv(1024)
except Timeout:
# No data after 5 seconds
"""
return FDReady(fd, read=True, timeout=timeout)
def writable(fd, timeout=None):
"""
A task that yields the result of this function will be resumed
when fd is writable. If timeout is not None, a Timeout exception
will be raised in the yielding task if fd is not writable after
timeout seconds have elapsed. For example:
try:
yield writable(sock, timeout=5)
nsent = sock.send(data)
except Timeout:
# Can't send after 5 seconds
"""
return FDReady(fd, write=True, timeout=timeout)
################################################################################
#
# FDAction class and related functions
#
################################################################################
class FDAction(FDReady):
"""
A task that yields an instance of this class will be suspended
until an I/O operation on a specified file descriptor is complete.
"""
def __init__(self, fd, func, args=(), kwargs={}, read=False, write=False,
exc=False):
"""
Resume the yielding task when fd is ready for reading,
writing, and/or "exceptional" condition handling. fd can be
any object accepted by select.select() (meaning an integer or
an object with a fileno() method that returns an integer).
Any exception raised by select() due to fd will be re-raised
in the yielding task.
The value of the yield expression will be the result of
calling func with the specified args and kwargs (which
presumably performs a read, write, or other I/O operation on
fd). If func raises an exception, it will be re-raised in the
yielding task. Thus, FDAction is really just a convenient
subclass of FDReady that requests that the task manager
perform an I/O operation on the calling task's behalf.
If kwargs contains a timeout argument that is not None, a
Timeout exception will be raised in the yielding task if fd is
not ready after timeout seconds have elapsed.
"""
timeout = kwargs.pop('timeout', None)
super(FDAction, self).__init__(fd, read, write, exc, timeout)
self.func = func
self.args = args
self.kwargs = kwargs
def _eval(self):
return self.func(*(self.args), **(self.kwargs))
def read(fd, *args, **kwargs):
"""
A task that yields the result of this function will be resumed
when fd is readable, and the value of the yield expression will be
the result of reading from fd. If a timeout keyword is given and
is not None, a Timeout exception will be raised in the yielding
task if fd is not readable after timeout seconds have elapsed.
Other arguments will be passed to the read function (os.read() if
fd is an integer, fd.read() otherwise). For example:
try:
data = (yield read(fd, 1024, timeout=5))
except Timeout:
# No data after 5 seconds
"""
func = (partial(os.read, fd) if _is_file_descriptor(fd) else fd.read)
return FDAction(fd, func, args, kwargs, read=True)
def readline(fd, *args, **kwargs):
"""
A task that yields the result of this function will be resumed
when fd is readable, and the value of the yield expression will be
the result of reading a line from fd. If a timeout keyword is
given and is not None, a Timeout exception will be raised in the
yielding task if fd is not readable after timeout seconds have
elapsed. Other arguments will be passed to fd.readline(). For
example:
try:
data = (yield readline(fd, timeout=5))
except Timeout:
# No data after 5 seconds
"""
return FDAction(fd, fd.readline, args, kwargs, read=True)
def write(fd, *args, **kwargs):
"""
A task that yields the result of this function will be resumed
when fd is writable, and the value of the yield expression will be
the result of writing to fd. If a timeout keyword is given and is
not None, a Timeout exception will be raised in the yielding task
if fd is not writable after timeout seconds have elapsed. Other
arguments will be passed to the write function (os.write() if fd
is an integer, fd.write() otherwise). For example:
try:
nbytes = (yield write(fd, data, timeout=5))
except Timeout:
# Can't write after 5 seconds
"""
func = (partial(os.write, fd) if _is_file_descriptor(fd) else fd.write)
return FDAction(fd, func, args, kwargs, write=True)
def accept(sock, *args, **kwargs):
"""
A task that yields the result of this function will be resumed
when sock is readable, and the value of the yield expression will
be the result of accepting a new connection on sock. If a timeout
keyword is given and is not None, a Timeout exception will be
raised in the yielding task if sock is not readable after timeout
seconds have elapsed. Other arguments will be passed to
sock.accept(). For example:
try:
conn, address = (yield accept(sock, timeout=5))
except Timeout:
# No connections after 5 seconds
"""
return FDAction(sock, sock.accept, args, kwargs, read=True)
def recv(sock, *args, **kwargs):
"""
A task that yields the result of this function will be resumed
when sock is readable, and the value of the yield expression will
be the result of receiving from sock. If a timeout keyword is
given and is not None, a Timeout exception will be raised in the
yielding task if sock is not readable after timeout seconds have
elapsed. Other arguments will be passed to sock.recv(). For
example:
try:
data = (yield recv(sock, 1024, timeout=5))
except Timeout:
# No data after 5 seconds
"""
return FDAction(sock, sock.recv, args, kwargs, read=True)
def recvfrom(sock, *args, **kwargs):
"""
A task that yields the result of this function will be resumed
when sock is readable, and the value of the yield expression will
be the result of receiving from sock. If a timeout keyword is
given and is not None, a Timeout exception will be raised in the
yielding task if sock is not readable after timeout seconds have
elapsed. Other arguments will be passed to sock.recvfrom(). For
example:
try:
data, address = (yield recvfrom(sock, 1024, timeout=5))
except Timeout:
# No data after 5 seconds
"""
return FDAction(sock, sock.recvfrom, args, kwargs, read=True)
def send(sock, *args, **kwargs):
"""
A task that yields the result of this function will be resumed
when sock is writable, and the value of the yield expression will
be the result of sending to sock. If a timeout keyword is given
and is not None, a Timeout exception will be raised in the
yielding task if sock is not writable after timeout seconds have
elapsed. Other arguments will be passed to the sock.send(). For
example:
try:
nsent = (yield send(sock, data, timeout=5))
except Timeout:
# Can't send after 5 seconds
"""
return FDAction(sock, sock.send, args, kwargs, write=True)
def sendto(sock, *args, **kwargs):
"""
A task that yields the result of this function will be resumed
when sock is writable, and the value of the yield expression will
be the result of sending to sock. If a timeout keyword is given
and is not None, a Timeout exception will be raised in the
yielding task if sock is not writable after timeout seconds have
elapsed. Other arguments will be passed to the sock.sendto().
For example:
try:
nsent = (yield sendto(sock, data, address, timeout=5))
except Timeout:
# Can't send after 5 seconds
"""
return FDAction(sock, sock.sendto, args, kwargs, write=True)
################################################################################
#
# Queue and _QueueAction classes
#
################################################################################
class Queue(object):
"""
A multi-producer, multi-consumer FIFO queue (similar to
Queue.Queue) that can be used for exchanging data between tasks
"""
def __init__(self, contents=(), maxsize=0):
"""
Create a new Queue instance. contents is a sequence (empty by
default) containing the initial contents of the queue. If
maxsize is greater than 0, the queue will hold a maximum of
maxsize items, and put() will block until space is available
in the queue.
"""
self.maxsize = int(maxsize)
self._queue = collections.deque(contents)
def __len__(self):
'Return the number of items in the queue'
return len(self._queue)
def _get(self):
return self._queue.popleft()
def _put(self, item):
self._queue.append(item)
def empty(self):
'Return True is the queue is empty, False otherwise'
return (len(self) == 0)
def full(self):
'Return True is the queue is full, False otherwise'
return ((len(self) >= self.maxsize) if (self.maxsize > 0) else False)
def get(self, timeout=None):
"""
A task that yields the result of this method will be resumed
when an item is available in the queue, and the value of the
yield expression will be the item. If timeout is not None, a
Timeout exception will be raised in the yielding task if an
item is not available after timeout seconds have elapsed. For
example:
try:
item = (yield queue.get(timeout=5))
except Timeout:
# No item available after 5 seconds
"""
return _QueueAction(self, timeout=timeout)
def put(self, item, timeout=None):
"""
A task that yields the result of this method will be resumed
when item has been added to the queue. If timeout is not
None, a Timeout exception will be raised in the yielding task
if no space is available after timeout seconds have elapsed.
For example:
try:
yield queue.put(item, timeout=5)
except Timeout:
# No space available after 5 seconds
"""
return _QueueAction(self, item, timeout=timeout)
class _QueueAction(YieldCondition):
NO_ITEM = object()
def __init__(self, queue, item=NO_ITEM, timeout=None):
super(_QueueAction, self).__init__(timeout)
if not isinstance(queue, Queue):
raise TypeError("'queue' must be a Queue instance")
self.queue = queue
self.item = item
################################################################################
#
# SmartQueue and _SmartQueueAction classes
#
################################################################################
class SmartQueue(object):
"""
A multi-producer, multi-consumer FIFO queue (similar to
Queue.Queue) that can be used for exchanging data between tasks.
The difference with Queue is that this implements filtering criteria
on get and allows multiple get to be signalled for the same put.
On the downside, this uses list instead of deque and has lower
performance.
"""
def __init__(self, contents=(), maxsize=0):
"""
Create a new Queue instance. contents is a sequence (empty by
default) containing the initial contents of the queue. If
maxsize is greater than 0, the queue will hold a maximum of
maxsize items, and put() will block until space is available
in the queue.
"""
self.maxsize = int(maxsize)
self._pending = list(contents)
def __len__(self):
'Return the number of items in the queue'
return len(self._pending)
def _get(self, criteria=None):
#self._pending = filter(lambda x: x[1]<=now, self._pending) # remove expired ones
if criteria:
found = filter(lambda x: criteria(x), self._pending) # check any matching criteria
if found:
self._pending.remove(found[0])
return found[0]
else:
return None
else:
return self._pending.pop(0) if self._pending else None
def _put(self, item):
self._pending.append(item)
def empty(self):
'Return True is the queue is empty, False otherwise'
return (len(self) == 0)
def full(self):
'Return True is the queue is full, False otherwise'
return ((len(self) >= self.maxsize) if (self.maxsize > 0) else False)
def get(self, timeout=None, criteria=None):
"""
A task that yields the result of this method will be resumed
when an item is available in the queue and the item matches the
given criteria (a function, usually lambda), and the value of the
yield expression will be the item. If timeout is not None, a
Timeout exception will be raised in the yielding task if an
item is not available after timeout seconds have elapsed. For
example:
try:
item = (yield queue.get(timeout=5, criteria=lambda x: x.name='kundan'))
except Timeout:
# No item available after 5 seconds
"""
return _SmartQueueAction(self, timeout=timeout, criteria=criteria)
def put(self, item, timeout=None):
"""
A task that yields the result of this method will be resumed
when item has been added to the queue. If timeout is not
None, a Timeout exception will be raised in the yielding task
if no space is available after timeout seconds have elapsed.
TODO: Otherwise if space is available, the timeout specifies how
long to keep the item in the queue before discarding it if it
is not fetched in a get. In this case it doesnot throw exception.
For example:
try:
yield queue.put(item, timeout=5)
except Timeout:
# No space available after 5 seconds
"""
return _SmartQueueAction(self, item, timeout=timeout)
class _SmartQueueAction(YieldCondition):
NO_ITEM = object()
def __init__(self, queue, item=NO_ITEM, timeout=None, criteria=None):
super(_SmartQueueAction, self).__init__(timeout)
if not isinstance(queue, SmartQueue):
raise TypeError("'queue' must be a SmartQueue instance")
self.queue = queue
self.item = item
self.criteria = criteria
self.expires = (timeout is not None) and (time.time() + timeout) or 0
################################################################################
#
# TaskManager class
#
################################################################################
class TaskManager(object):
"""
Engine for running a set of cooperatively-multitasking tasks
within a single Python thread
"""
def __init__(self):
"""
Create a new TaskManager instance. Generally, there will only
be one of these per Python process. If you want to run two
existing instances simultaneously, merge them first, then run
one or the other.
"""
self._queue = collections.deque()
self._read_waits = set()
self._write_waits = set()
self._exc_waits = set()
self._queue_waits = collections.defaultdict(self._double_deque)
self._timeouts = []
@staticmethod
def _double_deque():
return (collections.deque(), collections.deque())
def merge(self, other):
"""
Merge this TaskManager with another. After the merge, the two
objects share the same (merged) internal data structures, so
either can be used to manage the combined task set.
"""
if not isinstance(other, TaskManager):
raise TypeError("'other' must be a TaskManager instance")
# Merge the data structures
self._queue.extend(other._queue)
self._read_waits |= other._read_waits
self._write_waits |= other._write_waits
self._exc_waits |= other._exc_waits
self._queue_waits.update(other._queue_waits)
self._timeouts.extend(other._timeouts)
heapq.heapify(self._timeouts)
# Make other reference the merged data structures. This is
# necessary because other's tasks may reference and use other
# (e.g. to add a new task in response to an event).
other._queue = self._queue
other._read_waits = self._read_waits
other._write_waits = self._write_waits
other._exc_waits = self._exc_waits
other._queue_waits = self._queue_waits
other._timeouts = self._timeouts
def add(self, task):
'Add a new task (i.e. a generator instance) to the run queue'
if not isinstance(task, types.GeneratorType):
raise TypeError("'task' must be a generator")
self._enqueue(task)
def _enqueue(self, task, input=None, exc_info=()):
self._queue.append((task, input, exc_info))
def run(self):
"""
Call run_next() repeatedly until there are no tasks that are
currently runnable, waiting for I/O, or waiting to time out.
Note that this method can block indefinitely (e.g. if there
are only I/O waits and no timeouts). If this is unacceptable,
use run_next() instead.
"""
while self.has_runnable() or self.has_io_waits() or self.has_timeouts():
self.run_next()
def has_runnable(self):
"""
Return True is there are runnable tasks in the queue, False
otherwise
"""
return bool(self._queue)
def has_io_waits(self):
"""
Return True is there are tasks waiting for I/O, False
otherwise
"""
return bool(self._read_waits or self._write_waits or self._exc_waits)
def has_timeouts(self):
"""
Return True is there are tasks with pending timeouts, False
otherwise
"""
return bool(self._timeouts)
def run_next(self, timeout=None):
"""
Perform one iteration of the run cycle: check whether any
pending I/O operations can be performed, check whether any
timeouts have expired, then run all currently runnable tasks.
The timeout argument specifies the maximum time to wait for
some task to become runnable. If timeout is None and there
are no currently runnable tasks, but there are tasks waiting
to perform I/O or time out, then this method will block until
at least one of the waiting tasks becomes runnable. To
prevent this method from blocking indefinitely, use timeout to
specify the maximum number of seconds to wait.
If there are runnable tasks in the queue when run_next() is
called, then it will check for I/O readiness using a
non-blocking call to select() (i.e. a poll), and only
already-expired timeouts will be handled. This ensures both
that the task manager is never idle when tasks can be run and
that tasks waiting for I/O never starve.
"""
while self.has_io_waits():
if self._handle_io_waits(self._fix_run_timeout(timeout)) or self.has_runnable(): break
if self.has_timeouts():
self._handle_timeouts(self._fix_run_timeout(timeout))
# Run all tasks currently in the queue
#for dummy in xrange(len(self._queue)):
while len(self._queue) > 0:
task, input, exc_info = self._queue.popleft()
try:
if exc_info:
output = task.throw(*exc_info)
else:
output = task.send(input)
except StopIteration, e:
if isinstance(task, _ChildTask):
if not e.args:
output = None
elif len(e.args) == 1:
output = e.args[0]
else:
output = e.args
self._enqueue(task.parent, input=output)
except:
if isinstance(task, _ChildTask):
# Propagate exception to parent
self._enqueue(task.parent, exc_info=sys.exc_info())
else:
# No parent task, so just die
raise
else:
self._handle_task_output(task, output)
def _fix_run_timeout(self, timeout):
if self.has_runnable():
# Don't block if there are tasks in the queue
timeout = 0.0
elif self.has_timeouts():
# If there are timeouts, block only until the first expiration
expiration_timeout = max(0.0, self._timeouts[0][0] - time.time())
if (timeout is None) or (timeout > expiration_timeout):
timeout = expiration_timeout
return timeout
def _handle_io_waits(self, timeout):
# The error handling here is (mostly) borrowed from Twisted
try:
read_ready, write_ready, exc_ready = \
select.select(self._read_waits,
self._write_waits,