-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathcspthread.py
More file actions
1013 lines (848 loc) · 32 KB
/
Copy pathcspthread.py
File metadata and controls
1013 lines (848 loc) · 32 KB
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
#!/usr/bin/env python
"""Communicating sequential processes, in Python.
When using CSP Python as a DSL, this module will normally be imported
via the statement 'from csp.cspthread import *'.
Copyright (C) Sarah Mount, 2009-10.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have rceeived a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
"""
__author__ = 'Sarah Mount <s.mount@wlv.ac.uk>'
__date__ = '2010-05-16'
#DEBUG = True
DEBUG = False
from functools import wraps # Easy decorators
import copy
import gc
import inspect
import logging
import os
import random
import sys
import tempfile
import threading
import time
import uuid
try:
import cPickle as pickle # Faster, only in Python 2.x
except ImportError:
import pickle
try: # Python optimisation compiler
import psyco
psyco.full()
except ImportError:
print ( 'No available optimisation' )
### Names exported by this module
__all__ = ['set_debug', 'CSPProcess', 'CSPServer', 'Alt',
'Par', 'Seq', 'Guard', 'Channel', 'FileChannel',
'process', 'forever', 'Skip']
### Seeded random number generator (16 bytes)
_RANGEN = random.Random(os.urandom(16))
### CONSTANTS
_BUFFSIZE = 1024
class CorruptedData(Exception):
"""Used to verify that data has come from an honest source.
"""
def __init__(self):
super(CorruptedData, self).__init__()
return
def __str__(self):
return 'Data sent with incorrect authentication key.'
class NoGuardInAlt(Exception):
"""Raised when an Alt has no guards to select.
"""
def __init__(self):
super(NoGuardInAlt, self).__init__()
return
def __str__(self):
return 'Every Alt must have at least one guard.'
### Special constants / exceptions for termination and mobility
### Better not to use classes/objects here or pickle will get confused
### by the way that csp.__init__ manages the namespace.
_POISON = ';;;__POISON__;;;'
"""Used as special data sent down a channel to invoke termination."""
class ChannelPoison(Exception):
"""Used to poison a processes and propagate to all known channels.
"""
def __init__(self):
super(ChannelPoison, self).__init__()
return
def __str__(self):
return 'Posioned channel exception.'
### DEBUGGING
def set_debug(status):
global DEBUG
DEBUG = status
logging.basicConfig(level=logging.NOTSET,
stream=sys.stdout)
logging.info("Using multiprocessing version of python-csp.")
return
### Fundamental CSP concepts -- Processes, Channels, Guards
class _CSPOpMixin(object):
"""Mixin class used for operator overloading in CSP process types.
"""
def __init__(self):
return
def spawn(self):
"""Start only if self is not running."""
if not self._Thread__started.is_set():
threading.Thread.start(self)
return
def start(self):
"""Start only if self is not running."""
if not self._Thread__started.is_set():
threading.Thread.start(self)
threading.Thread.join(self)
def join(self):
"""Join only if self is running."""
if self._Thread__started.is_set():
threading.Thread.join(self)
def referent_visitor(self, referents):
for obj in referents:
if obj is self or obj is None:
continue
if isinstance(obj, Channel):
obj.poison()
elif ((hasattr(obj, '__getitem__') or hasattr(obj, '__iter__')) and
not isinstance(obj, str)):
self.referent_visitor(obj)
elif isinstance(obj, CSPProcess):
self.referent_visitor(obj.args + tuple(obj.kwargs.values()))
elif hasattr(obj, '__dict__'):
self.referent_visitor(list(obj.__dict__.values()))
return
def terminate(self):
"""Terminate only if self is running.
FIXME: This doesn't work yet...
"""
if self._Thread__started.is_set():
logging.debug('%s terminating now...' % self.getName())
return #threading.Thread._Thread__stop(self) # Sets an event object
def __gt__(self, other):
"""Implementation of CSP Seq."""
assert _is_csp_type(other)
seq = Seq(self, other)
seq.start()
return seq
def __mul__(self, n):
assert n > 0
clone = None
for i in range(n):
clone = copy.copy(self)
clone.start()
return
def __rmul__(self, n):
assert n > 0
clone = None
for i in range(n):
clone = copy.copy(self)
clone.start()
return
class CSPProcess(threading.Thread, _CSPOpMixin):
"""Implementation of CSP processes.
Not intended to be used in client code. Use @process instead.
"""
def __init__(self, func, *args, **kwargs):
threading.Thread.__init__(self,
target=func,
args=(args),
kwargs=kwargs)
assert inspect.isfunction(func) # Check we aren't using objects
assert not inspect.ismethod(func) # Check we aren't using objects
_CSPOpMixin.__init__(self)
for arg in list(args) + list(kwargs.values()):
if _is_csp_type(arg):
arg.enclosing = self
self.enclosing = None
return
def getPid(self):
"""Return thread ident.
The name of this method ensures that the CSPProcess interface
in this module is identical to the one defined in
cspprocess.py.
"""
return self.ident
def __ifloordiv__(self, proclist):
"""
Run this process in parallel with a list of others.
"""
assert hasattr(proclist, '__iter__')
par = Par(self, *proclist)
par.start()
return
def __str__(self):
return 'CSPProcess running in TID %s' % self.getName()
def run(self): #, event=None):
"""Called automatically when the L{start} methods is called.
"""
try:
self._Thread__target(*self._Thread__args, **self._Thread__kwargs)
except ChannelPoison:
logging.debug('%s in %g got ChannelPoison exception' %
(str(self), self.getPid()))
self.referent_visitor(self._Thread__args +
tuple(self._Thread__kwargs.values()))
except KeyboardInterrupt:
sys.exit()
except Exception:
typ, excn, tback = sys.exc_info()
sys.excepthook(typ, excn, tback)
return
def __del__(self):
"""Run the garbage collector automatically on deletion of this
object.
This prevents the "Winder Bug" found in tests/winder_bug of
the distribution, where successive process graphs are created
in memory and, when the "outer" CSPProcess object returns from
its .start() method the process graph is not garbage
collected. This accretion of garbage can cause degenerate
behaviour which is difficult to debug, such as a program
pausing indefinitely on Channel creation.
"""
if gc is not None:
gc.collect()
return
class CSPServer(CSPProcess):
"""Implementation of CSP server processes.
Not intended to be used in client code. Use @forever instead.
"""
def __init__(self, func, *args, **kwargs):
CSPProcess.__init__(self, func, *args, **kwargs)
return
def __str__(self):
return 'CSPServer running in PID %s' % self.getPid()
def run(self): #, event=None):
"""Called automatically when the L{start} methods is called.
"""
try:
generator = self._Thread__target(*self._Thread__args, **self._Thread__kwargs)
while sys.gettrace() is None:
next(generator)
else:
# If the tracer is running execute the target only once.
next(generator)
logging.info('Server process detected a tracer running.')
return
except ChannelPoison:
logging.debug('%s in %g got ChannelPoison exception' %
(str(self), self.getPid()))
self.referent_visitor(self._Thread__args + tuple(self._Thread__kwargs.values()))
# if self._popen is not None: self.terminate()
except KeyboardInterrupt:
sys.exit()
except Exception:
typ, excn, tback = sys.exc_info()
sys.excepthook(typ, excn, tback)
return
class Alt(_CSPOpMixin):
"""CSP select (OCCAM ALT) process.
What should happen if a guard is poisoned?
"""
def __init__(self, *args):
super(Alt, self).__init__()
for arg in args:
assert isinstance(arg, Guard)
self.guards = list(args)
self.last_selected = None
def poison(self):
"""Poison the last selected guard and unlink from the guard list.
Sets self.last_selected to None.
"""
logging.debug(str(type(self.last_selected)))
self.last_selected.disable() # Just in case
try:
self.last_selected.poison()
except Exception:
pass
logging.debug('Poisoned last selected.')
self.guards.remove(self.last_selected)
logging.debug('%i guards' % len(self.guards))
self.last_selected = None
def _preselect(self):
"""Check for special cases when any form of select() is called.
"""
if len(self.guards) == 0:
raise NoGuardInAlt()
elif len(self.guards) == 1:
logging.debug('Alt Selecting unique guard: %s' %
self.guards[0].name)
self.last_selected = self.guards[0]
while not self.guards[0].is_selectable():
self.guards[0].enable()
return self.guards[0].select()
return None
def select(self):
"""Randomly select from ready guards."""
if len(self.guards) < 2:
return self._preselect()
ready = []
while len(ready) == 0:
for guard in self.guards:
guard.enable()
logging.debug('Alt enabled all guards')
time.sleep(0.01) # Not sure about this.
ready = [guard for guard in self.guards if guard.is_selectable()]
logging.debug('Alt got %i items to choose from out of %i' %
(len(ready), len(self.guards)))
selected = _RANGEN.choice(ready)
self.last_selected = selected
for guard in self.guards:
if guard is not selected:
guard.disable()
return selected.select()
def fair_select(self):
"""Select a guard to synchronise with. Do not select the
previously selected guard (unless it is the only guard
available).
"""
if len(self.guards) < 2:
return self._preselect()
ready = []
while len(ready) == 0:
for guard in self.guards:
guard.enable()
logging.debug('Alt enabled all guards')
time.sleep(0.1) # Not sure about this.
ready = [guard for guard in self.guards if guard.is_selectable()]
logging.debug('Alt got %i items to choose from, out of %i' %
(len(ready), len(self.guards)))
selected = None
if self.last_selected in ready and len(ready) > 1:
ready.remove(self.last_selected)
logging.debug('Alt removed last selected from ready list')
selected = _RANGEN.choice(ready)
self.last_selected = selected
for guard in self.guards:
if guard is not selected:
guard.disable()
return selected.select()
def pri_select(self):
"""Select a guard to synchronise with, in order of
"priority". The guard with the lowest index in the L{guards}
list has the highest priority.
"""
if len(self.guards) < 2:
return self._preselect()
ready = []
while len(ready) == 0:
for guard in self.guards:
guard.enable()
logging.debug('Alt enabled all guards')
time.sleep(0.01) # Not sure about this.
ready = [guard for guard in self.guards if guard.is_selectable()]
logging.debug('Alt got %i items to choose from, out of %i' %
(len(ready), len(self.guards)))
self.last_selected = ready[0]
for guard in ready[1:]:
guard.disable()
return ready[0].select()
def __mul__(self, n):
assert n > 0
for i in range(n):
yield self.select()
return
def __rmul__(self, n):
assert n > 0
for i in range(n):
yield self.select()
return
class Par(threading.Thread, _CSPOpMixin):
"""Run CSP processes in parallel.
"""
def __init__(self, *procs, **kwargs):
super(Par, self).__init__(None)
self.procs = []
for proc in procs:
# FIXME: only catches shallow nesting.
if isinstance(proc, Par):
self.procs += proc.procs
else:
self.procs.append(proc)
for proc in self.procs:
proc.enclosing = self
logging.debug('%i processes in Par:' % len(self.procs))
return
def __ifloordiv__(self, proclist):
"""
Run this Par in parallel with a list of others.
"""
assert hasattr(proclist, '__iter__')
self.procs = []
for proc in proclist:
# FIXME: only catches shallow nesting.
if isinstance(proc, Par):
self.procs += proc.procs
else:
self.procs.append(proc)
for proc in self.procs:
proc.enclosing = self
logging.debug('%i processes added to Par by //=:' % len(self.procs))
self.start()
return
def __str__(self):
return 'CSP Par running in process %i.' % self.getPid()
def terminate(self):
"""Terminate the execution of this process.
"""
for proc in self.procs:
proc.terminate()
if self._Thread__started.is_set():
Thread._Thread__stop(self)
def getPid(self):
"""Return thread ident.
The name of this method ensures that the CSPProcess interface
in this module is identical to the one defined in
cspprocess.py.
"""
return self.ident
def start(self):
"""Run this process. Analogue of L{CSPProcess.run}.
"""
self.start()
def join(self):
for proc in self.procs:
proc.join()
return
def start(self):
"""Start then synchronize with the execution of parallel processes.
Return when all parallel processes have returned.
"""
try:
for proc in self.procs:
proc.spawn()
for proc in self.procs:
proc.join()
except ChannelPoison:
logging.debug('%s got ChannelPoison exception in %g' %
(str(self), self.getPid()))
self.referent_visitor(self._Thread__args + tuple(self._Thread__kwargs.values()))
except Exception:
typ, excn, tback = sys.exc_info()
sys.excepthook(typ, excn, tback)
return
def __len__(self):
return len(self.procs)
def __getitem__(self, index):
try:
return self.procs[index]
except IndexError:
raise IndexError
def __setitem__(self, index, value):
assert isinstance(value, CSPProcess)
self.procs[index] = value
return
def __contains__(self, proc):
return proc in self.procs
class Seq(threading.Thread, _CSPOpMixin):
"""Run CSP processes sequentially.
"""
def __init__(self, *procs):
super(Seq, self).__init__()
self.procs = []
for proc in procs:
# FIXME: only catches shallow nesting.
if isinstance(proc, Seq):
self.procs += proc.procs
else:
self.procs.append(proc)
for proc in self.procs:
proc.enclosing = self
return
def __str__(self):
return 'CSP Seq running in process %i.' % self.getPid()
def start(self):
"""Start this process running.
"""
try:
for proc in self.procs:
_CSPOpMixin.start(proc)
proc.join()
except ChannelPoison:
logging.debug('%s in %g got ChannelPoison exception' %
(str(self), self.getPid()))
self.referent_visitor(self._Thread__args + tuple(self._Thread__kwargs.values()))
except KeyboardInterrupt:
sys.exit()
except Exception:
typ, excn, tback = sys.exc_info()
sys.excepthook(typ, excn, tback)
return
### Guards and channels
class Guard(object):
"""Abstract class to represent CSP guards.
All methods must be overridden in subclasses.
"""
def is_selectable(self):
"""Should return C{True} if this guard can be selected by an L{Alt}.
"""
raise NotImplementedError('Must be implemented in subclass')
def enable(self):
"""Prepare for, but do not commit to a synchronisation.
"""
raise NotImplementedError('Must be implemented in subclass')
def disable(self):
"""Roll back from an L{enable} call.
"""
raise NotImplementedError('Must be implemented in subclass')
def select(self):
"""Commit to a synchronisation started by L{enable}.
"""
raise NotImplementedError('Must be implemented in subclass')
def poison(self):
"""Terminate all processes attached to this guard.
"""
pass
def __str__(self):
return 'CSP Guard: must be subclassed.'
def __or__(self, other):
assert isinstance(other, Guard)
return Alt(self, other).select()
def __ror__(self, other):
assert isinstance(other, Guard)
return Alt(self, other).select()
class Channel(Guard):
"""CSP Channel objects.
In python-csp there are two sorts of channel. In JCSP terms these
are Any2Any, Alting channels. However, each channel creates an
operating system level pipe. Since this is a file object the
number of channels a program can create is limited to the maximum
number of files the operating system allows to be open at any one
time. To avoid this bottleneck use L{FileChannel} objects, which
close the file descriptor used for IPC after every read or write
operations. Read and write operations are, however, over 20 time
slower when performed on L{FileChannel} objects.
Subclasses of C{Channel} must call L{_setup()} in their
constructor and override L{put}, L{get}, L{__del__},
L{__getstate__} and L{__setstate__}, the latter two methods for
pickling.
"""
def __init__(self):
self.name = uuid.uuid1()
self._wlock = None # Write lock protects from races between writers.
self._rlock = None # Read lock protects from races between readers.
self._plock = None
self._available = None # Released if writer has made data available.
self._taken = None # Released if reader has taken data.
self._is_alting = None # True if engaged in an Alt synchronisation.
self._is_selectable = None # True if can be selected by an Alt.
self._has_selected = None # True if already been committed to select.
self._store = None # Holds value transferred by channel
self._poisoned = False
self._setup()
super(Channel, self).__init__()
logging.debug('Channel created: %s' % self.name)
return
def _setup(self):
"""Set up synchronisation.
MUST be called in __init__ of this class and all subclasses.
"""
# Process-safe synchronisation.
self._wlock = threading.RLock() # Write lock.
self._rlock = threading.RLock() # Read lock.
self._plock = threading.Lock() # Fix poisoning.
self._available = threading.Semaphore(0)
self._taken = threading.Semaphore(0)
# Process-safe synchronisation for CSP Select / Occam Alt.
self._is_alting = False
self._is_selectable = False
# Kludge to say a select has finished (to prevent the channel
# from being re-enabled). If values were really process safe
# we could just have writers set _is_selectable and read that.
self._has_selected = False
def __getstate__(self):
"""Return state required for pickling."""
state = [self._available._Semaphore__value,
self._taken._Semaphore__value,
self._is_alting,
self._is_selectable,
self._has_selected]
if self._available._Semaphore__value > 0:
obj = self.get()
else:
obj = None
state.append(obj)
return state
def __setstate__(self, state):
"""Restore object state after unpickling."""
self._wlock = threading.RLock() # Write lock.
self._rlock = threading.RLock() # Read lock.
self._available = threading.Semaphore(state[0])
self._taken = threading.Semaphore(state[1])
self._is_alting = state[2]
self._is_selectable = state[3]
self._has_selected = state[4]
if state[5] is not None:
self.put(state[5])
return
def put(self, item):
"""Put C{item} on a process-safe store.
"""
self.checkpoison()
self._store = pickle.dumps(item, protocol=1)
def get(self):
"""Get a Python object from a process-safe store.
"""
self.checkpoison()
item = pickle.loads(self._store)
self._store = None
return item
def is_selectable(self):
"""Test whether Alt can select this channel.
"""
logging.debug('Alt THINKS _is_selectable IS: %s' %
str(self._is_selectable))
self.checkpoison()
return self._is_selectable
def write(self, obj):
"""Write a Python object to this channel.
"""
self.checkpoison()
logging.debug('+++ Write on Channel %s started.' % self.name)
with self._wlock: # Protect from races between multiple writers.
# If this channel has already been selected by an Alt then
# _has_selected will be True, blocking other readers. If a
# new write is performed that flag needs to be reset for
# the new write transaction.
self._has_selected = False
# Make the object available to the reader.
self.put(obj)
# Announce the object has been released to the reader.
self._available.release()
logging.debug('++++ Writer on Channel %s: _available: %i _taken: %i. ' %
(self.name, self._available._Semaphore__value,
self._taken._Semaphore__value))
# Block until the object has been read.
self._taken.acquire()
# Remove the object from the channel.
logging.debug('+++ Write on Channel %s finished.' % self.name)
return
def read(self):
"""Read (and return) a Python object from this channel.
"""
self.checkpoison()
logging.debug('+++ Read on Channel %s started.' % self.name)
with self._rlock: # Protect from races between multiple readers.
# Block until an item is in the Channel.
logging.debug('++++ Reader on Channel %s: _available: %i _taken: %i. ' %
(self.name, self._available._Semaphore__value,
self._taken._Semaphore__value))
self._available.acquire()
# Get the item.
obj = self.get()
# Announce the item has been read.
self._taken.release()
logging.debug('+++ Read on Channel %s finished.' % self.name)
return obj
def enable(self):
"""Enable a read for an Alt select.
MUST be called before L{select()} or L{is_selectable()}.
"""
self.checkpoison()
# Prevent re-synchronization.
if (self._has_selected or self._is_selectable):
return
self._is_alting = True
with self._rlock:
# Attempt to acquire _available.
time.sleep(0.00001) # Won't work without this -- why?
if self._available.acquire(blocking=False):
self._is_selectable = True
else:
self._is_selectable = False
logging.debug('Enable on guard %s _is_selectable: %s _available: %s'
% (self.name, str(self._is_selectable),
str(self._available)))
return
def disable(self):
"""Disable this channel for Alt selection.
MUST be called after L{enable} if this channel is not selected.
"""
self.checkpoison()
self._is_alting = False
if self._is_selectable:
with self._rlock:
self._available.release()
self._is_selectable = False
return
def select(self):
"""Complete a Channel read for an Alt select.
"""
self.checkpoison()
logging.debug('channel select starting')
assert self._is_selectable == True
with self._rlock:
logging.debug('got read lock on channel %s _available: %s'
% (self.name, str(self._available._Semaphore__value)))
# Obtain object on Channel.
obj = self.get()
logging.debug('Writer got obj')
# Notify write() that object is taken.
self._taken.release()
logging.debug('Writer released _taken')
# Reset flags to ensure a future read / enable / select.
self._is_selectable = False
self._is_alting = False
self._has_selected = True
logging.debug('reset bools')
if obj == _POISON:
self.poison()
raise ChannelPoison()
return obj
def __str__(self):
return 'Channel using OS pipe for IPC.'
def checkpoison(self):
with self._plock:
if self._poisoned:
raise ChannelPoison()
return
def poison(self):
"""Poison a channel causing all processes using it to terminate.
"""
with self._plock:
self._poisoned = True
# Avoid race conditions on any waiting readers / writers.
self._available.release()
self._taken.release()
return
class FileChannel(Channel):
"""Channel objects using files on disk.
C{FileChannel} objects close their files after each read or write
operation. The advantage of this is that client code can create as
many C{FileChannel} objects as it wishes (unconstrained by the
operating system's maximum number of open files). In return there
is a performance hit -- reads and writes are around 10 x slower on
C{FileChannel} objects compared to L{Channel} objects.
"""
def __init__(self):
self.name = uuid.uuid1()
self._wlock = None # Write lock.
self._rlock = None # Read lock.
self._available = None
self._taken = None
self._is_alting = None
self._is_selectable = None
self._has_selected = None
# Process-safe store.
file_d, self._fname = tempfile.mkstemp()
os.close(file_d)
self._setup()
return
def __getstate__(self):
"""Return state required for pickling."""
state = [pickle.dumps(self._available, protocol=1),
pickle.dumps(self._taken, protocol=1),
pickle.dumps(self._is_alting, protocol=1),
pickle.dumps(self._is_selectable, protocol=1),
pickle.dumps(self._has_selected, protocol=1),
self._fname]
if self._available.getValue() > 0:
obj = self.get()
else:
obj = None
state.append(obj)
return state
def __setstate__(self, state):
"""Restore object state after unpickling."""
self._wlock = threading.RLock() # Write lock.
self._rlock = threading.RLock() # Read lock.
self._available = pickle.loads(state[0])
self._taken = pickle.loads(state[1])
self._is_alting = pickle.loads(state[2])
self._is_selectable = pickle.loads(state[3])
self._has_selected = pickle.loads(state[4])
self._fname = state[5]
if state[6] is not None:
self.put(state[6])
return
def put(self, item):
"""Put C{item} on a process-safe store.
"""
file_d = file(self._fname, 'w')
file_d.write(pickle.dumps(item, protocol=1))
file_d.flush()
file_d.close()
return
def get(self):
"""Get a Python object from a process-safe store.
"""
stored = ''
while stored == '':
file_d = file(self._fname, 'r')
stored = file_d.read()
file_d.close()
# Unlinking here ensures that FileChannel objects exhibit the
# same semantics as Channel objects.
os.unlink(self._fname)
obj = pickle.loads(stored)
return obj
def __del__(self):
if os.path.exists(self._fname):
# Necessary if the Channel has been deleted by poisoning.
os.unlink(self._fname)
return
def __str__(self):
return 'Channel using files for IPC.'
### Function decorators
def process(func):
"""Decorator to turn a function into a CSP process.
Note that the function itself will not be a CSPProcess object, but
will generate a CSPProcess object when called.
"""
@wraps(func)
def _call(*args, **kwargs):
"""Call the target function."""
return CSPProcess(func, *args, **kwargs)
return _call
def forever(func):
"""Decorator to turn a function into a CSP server process.
It is preferable to use this rather than @process, to enable the
CSP tracer to terminate correctly and produce a CSP model, or
other debugging information.
"""
@wraps(func)
def _call(*args, **kwargs):
"""Call the target function."""
return CSPServer(func, *args, **kwargs)
return _call
### List of CSP based types (class names). Used by _is_csp_type.
_CSPTYPES = [CSPProcess, Par, Seq, Alt]
def _is_csp_type(name):
"""Return True if name is any type of CSP process."""
for typ in _CSPTYPES:
if isinstance(name, typ):
return True
return False
def _nop():
return
class Skip(Guard, CSPProcess):
"""Guard which will always return C{True}. Useful in L{Alt}s where
the programmer wants to ensure that L{Alt.select} will always
synchronise with at least one guard.
"""
def __init__(self):
Guard.__init__(self)
CSPProcess.__init__(self, _nop)
self.name = '__Skip__'
return
def is_selectable(self):
"""Skip is always selectable."""
return True
def enable(self):
"""Has no effect."""