home *** CD-ROM | disk | FTP | other *** search
/ Chip 2003 January / Chip_2003-01_cd2.bin / convert / eJayMp3Pro / mp3pro_demo.exe / THREADING.PYC (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2000-06-16  |  27.6 KB  |  732 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 1.5)
  3.  
  4. import sys
  5. import time
  6. import thread
  7. import traceback
  8. import StringIO
  9. _sys = sys
  10. del sys
  11. _time = time.time
  12. _sleep = time.sleep
  13. del time
  14. _start_new_thread = thread.start_new_thread
  15. _allocate_lock = thread.allocate_lock
  16. _get_ident = thread.get_ident
  17. del thread
  18. _print_exc = traceback.print_exc
  19. del traceback
  20. _StringIO = StringIO.StringIO
  21. del StringIO
  22. _VERBOSE = 0
  23. if __debug__:
  24.     
  25.     class _Verbose:
  26.         
  27.         def __init__(self, verbose = None):
  28.             if verbose is None:
  29.                 verbose = _VERBOSE
  30.             
  31.             self._Verbose__verbose = verbose
  32.  
  33.         
  34.         def _note(self, format, *args):
  35.             if self._Verbose__verbose:
  36.                 format = format % args
  37.                 format = '%s: %s\n' % (currentThread().getName(), format)
  38.                 _sys.stderr.write(format)
  39.             
  40.  
  41.  
  42. else:
  43.     
  44.     class _Verbose:
  45.         
  46.         def __init__(self, verbose = None):
  47.             pass
  48.  
  49.         
  50.         def _note(self, *args):
  51.             pass
  52.  
  53.  
  54. Lock = _allocate_lock
  55.  
  56. def RLock(*args, **kwargs):
  57.     return apply(_RLock, args, kwargs)
  58.  
  59.  
  60. class _RLock(_Verbose):
  61.     
  62.     def __init__(self, verbose = None):
  63.         _Verbose.__init__(self, verbose)
  64.         self._RLock__block = _allocate_lock()
  65.         self._RLock__owner = None
  66.         self._RLock__count = 0
  67.  
  68.     
  69.     def __repr__(self):
  70.         if self._RLock__owner:
  71.             pass
  72.         return '<%s(%s, %d)>' % (self.__class__.__name__, self._RLock__owner.getName(), self._RLock__count)
  73.  
  74.     
  75.     def acquire(self, blocking = 1):
  76.         me = currentThread()
  77.         if self._RLock__owner is me:
  78.             self._RLock__count = self._RLock__count + 1
  79.             if __debug__:
  80.                 self._note('%s.acquire(%s): recursive success', self, blocking)
  81.             
  82.             return 1
  83.         
  84.         rc = self._RLock__block.acquire(blocking)
  85.         if rc:
  86.             self._RLock__owner = me
  87.             self._RLock__count = 1
  88.             if __debug__:
  89.                 self._note('%s.acquire(%s): initial succes', self, blocking)
  90.             
  91.         elif __debug__:
  92.             self._note('%s.acquire(%s): failure', self, blocking)
  93.         
  94.         return rc
  95.  
  96.     
  97.     def release(self):
  98.         me = currentThread()
  99.         if not __debug__ and self._RLock__owner is me:
  100.             raise AssertionError, 'release() of un-acquire()d lock'
  101.         self._RLock__count = count = self._RLock__count - 1
  102.         if not count:
  103.             self._RLock__owner = None
  104.             self._RLock__block.release()
  105.             if __debug__:
  106.                 self._note('%s.release(): final release', self)
  107.             
  108.         elif __debug__:
  109.             self._note('%s.release(): non-final release', self)
  110.         
  111.  
  112.     
  113.     def _acquire_restore(self, .2):
  114.         (count, owner) = .2
  115.         self._RLock__block.acquire()
  116.         self._RLock__count = count
  117.         self._RLock__owner = owner
  118.         if __debug__:
  119.             self._note('%s._acquire_restore()', self)
  120.         
  121.  
  122.     
  123.     def _release_save(self):
  124.         if __debug__:
  125.             self._note('%s._release_save()', self)
  126.         
  127.         count = self._RLock__count
  128.         self._RLock__count = 0
  129.         owner = self._RLock__owner
  130.         self._RLock__owner = None
  131.         self._RLock__block.release()
  132.         return (count, owner)
  133.  
  134.     
  135.     def _is_owned(self):
  136.         return self._RLock__owner is currentThread()
  137.  
  138.  
  139.  
  140. def Condition(*args, **kwargs):
  141.     return apply(_Condition, args, kwargs)
  142.  
  143.  
  144. class _Condition(_Verbose):
  145.     
  146.     def __init__(self, lock = None, verbose = None):
  147.         _Verbose.__init__(self, verbose)
  148.         if lock is None:
  149.             lock = RLock()
  150.         
  151.         self._Condition__lock = lock
  152.         self.acquire = lock.acquire
  153.         self.release = lock.release
  154.         
  155.         try:
  156.             self._release_save = lock._release_save
  157.         except AttributeError:
  158.             pass
  159.  
  160.         
  161.         try:
  162.             self._acquire_restore = lock._acquire_restore
  163.         except AttributeError:
  164.             pass
  165.  
  166.         
  167.         try:
  168.             self._is_owned = lock._is_owned
  169.         except AttributeError:
  170.             pass
  171.  
  172.         self._Condition__waiters = []
  173.  
  174.     
  175.     def __repr__(self):
  176.         return '<Condition(%s, %d)>' % (self._Condition__lock, len(self._Condition__waiters))
  177.  
  178.     
  179.     def _release_save(self):
  180.         self._Condition__lock.release()
  181.  
  182.     
  183.     def _acquire_restore(self, x):
  184.         self._Condition__lock.acquire()
  185.  
  186.     
  187.     def _is_owned(self):
  188.         if self._Condition__lock.acquire(0):
  189.             self._Condition__lock.release()
  190.             return 0
  191.         else:
  192.             return 1
  193.  
  194.     
  195.     def wait(self, timeout = None):
  196.         me = currentThread()
  197.         if not __debug__ and self._is_owned():
  198.             raise AssertionError, 'wait() of un-acquire()d lock'
  199.         waiter = _allocate_lock()
  200.         waiter.acquire()
  201.         self._Condition__waiters.append(waiter)
  202.         saved_state = self._release_save()
  203.         if timeout is None:
  204.             waiter.acquire()
  205.             if __debug__:
  206.                 self._note('%s.wait(): got it', self)
  207.             
  208.         else:
  209.             endtime = _time() + timeout
  210.             delay = 1e-006
  211.             while 1:
  212.                 gotit = waiter.acquire(0)
  213.                 if gotit or _time() >= endtime:
  214.                     break
  215.                 
  216.                 _sleep(delay)
  217.                 if delay < 1.0:
  218.                     delay = delay * 2.0
  219.                 
  220.             if not gotit:
  221.                 if __debug__:
  222.                     self._note('%s.wait(%s): timed out', self, timeout)
  223.                 
  224.                 
  225.                 try:
  226.                     self._Condition__waiters.remove(waiter)
  227.                 except ValueError:
  228.                     pass
  229.  
  230.             elif __debug__:
  231.                 self._note('%s.wait(%s): got it', self, timeout)
  232.             
  233.         self._acquire_restore(saved_state)
  234.  
  235.     
  236.     def notify(self, n = 1):
  237.         me = currentThread()
  238.         if not __debug__ and self._is_owned():
  239.             raise AssertionError, 'notify() of un-acquire()d lock'
  240.         _Condition__waiters = self._Condition__waiters
  241.         waiters = _Condition__waiters[:n]
  242.         if not waiters:
  243.             if __debug__:
  244.                 self._note('%s.notify(): no waiters', self)
  245.             
  246.             return None
  247.         
  248.         if not n != 1 and 's':
  249.             pass
  250.         self._note('%s.notify(): notifying %d waiter%s', self, n, '')
  251.         for waiter in waiters:
  252.             waiter.release()
  253.             
  254.             try:
  255.                 _Condition__waiters.remove(waiter)
  256.             except ValueError:
  257.                 0
  258.                 0
  259.                 waiters
  260.             except:
  261.                 0
  262.  
  263.         
  264.  
  265.     
  266.     def notifyAll(self):
  267.         self.notify(len(self._Condition__waiters))
  268.  
  269.  
  270.  
  271. def Semaphore(*args, **kwargs):
  272.     return apply(_Semaphore, args, kwargs)
  273.  
  274.  
  275. class _Semaphore(_Verbose):
  276.     
  277.     def __init__(self, value = 1, verbose = None):
  278.         if not __debug__ and value >= 0:
  279.             raise AssertionError, 'Semaphore initial value must be >= 0'
  280.         _Verbose.__init__(self, verbose)
  281.         self._Semaphore__cond = Condition(Lock())
  282.         self._Semaphore__value = value
  283.  
  284.     
  285.     def acquire(self, blocking = 1):
  286.         rc = 0
  287.         self._Semaphore__cond.acquire()
  288.         while self._Semaphore__value == 0:
  289.             if not blocking:
  290.                 break
  291.             
  292.             self._Semaphore__cond.wait()
  293.         self._Semaphore__value = self._Semaphore__value - 1
  294.         rc = 1
  295.         self._Semaphore__cond.release()
  296.         return rc
  297.  
  298.     
  299.     def release(self):
  300.         self._Semaphore__cond.acquire()
  301.         self._Semaphore__value = self._Semaphore__value + 1
  302.         self._Semaphore__cond.notify()
  303.         self._Semaphore__cond.release()
  304.  
  305.  
  306.  
  307. def Event(*args, **kwargs):
  308.     return apply(_Event, args, kwargs)
  309.  
  310.  
  311. class _Event(_Verbose):
  312.     
  313.     def __init__(self, verbose = None):
  314.         _Verbose.__init__(self, verbose)
  315.         self._Event__cond = Condition(Lock())
  316.         self._Event__flag = 0
  317.  
  318.     
  319.     def isSet(self):
  320.         return self._Event__flag
  321.  
  322.     
  323.     def set(self):
  324.         self._Event__cond.acquire()
  325.         self._Event__flag = 1
  326.         self._Event__cond.notifyAll()
  327.         self._Event__cond.release()
  328.  
  329.     
  330.     def clear(self):
  331.         self._Event__cond.acquire()
  332.         self._Event__flag = 0
  333.         self._Event__cond.release()
  334.  
  335.     
  336.     def wait(self, timeout = None):
  337.         self._Event__cond.acquire()
  338.         if not (self._Event__flag):
  339.             self._Event__cond.wait(timeout)
  340.         
  341.         self._Event__cond.release()
  342.  
  343.  
  344. _counter = 0
  345.  
  346. def _newname(template = 'Thread-%d'):
  347.     global _counter
  348.     _counter = _counter + 1
  349.     return template % _counter
  350.  
  351. _active_limbo_lock = _allocate_lock()
  352. _active = { }
  353. _limbo = { }
  354.  
  355. class Thread(_Verbose):
  356.     __initialized = 0
  357.     
  358.     def __init__(self, group = None, target = None, name = None, args = (), kwargs = { }, verbose = None):
  359.         if not __debug__ and group is None:
  360.             raise AssertionError, 'group argument must be None for now'
  361.         _Verbose.__init__(self, verbose)
  362.         self._Thread__target = target
  363.         if not name:
  364.             pass
  365.         self._Thread__name = str(_newname())
  366.         self._Thread__args = args
  367.         self._Thread__kwargs = kwargs
  368.         self._Thread__daemonic = self._set_daemon()
  369.         self._Thread__started = 0
  370.         self._Thread__stopped = 0
  371.         self._Thread__block = Condition(Lock())
  372.         self._Thread__initialized = 1
  373.  
  374.     
  375.     def _set_daemon(self):
  376.         return currentThread().isDaemon()
  377.  
  378.     
  379.     def __repr__(self):
  380.         if not __debug__ and self._Thread__initialized:
  381.             raise AssertionError, 'Thread.__init__() was not called'
  382.         status = 'initial'
  383.         if self._Thread__started:
  384.             status = 'started'
  385.         
  386.         if self._Thread__stopped:
  387.             status = 'stopped'
  388.         
  389.         if self._Thread__daemonic:
  390.             status = status + ' daemon'
  391.         
  392.         return '<%s(%s, %s)>' % (self.__class__.__name__, self._Thread__name, status)
  393.  
  394.     
  395.     def start(self):
  396.         if not __debug__ and self._Thread__initialized:
  397.             raise AssertionError, 'Thread.__init__() not called'
  398.         if not __debug__ and not (self._Thread__started):
  399.             raise AssertionError, 'thread already started'
  400.         if __debug__:
  401.             self._note('%s.start(): starting thread', self)
  402.         
  403.         _active_limbo_lock.acquire()
  404.         _limbo[self] = self
  405.         _active_limbo_lock.release()
  406.         _start_new_thread(self._Thread__bootstrap, ())
  407.         self._Thread__started = 1
  408.         _sleep(1e-006)
  409.  
  410.     
  411.     def run(self):
  412.         if self._Thread__target:
  413.             apply(self._Thread__target, self._Thread__args, self._Thread__kwargs)
  414.         
  415.  
  416.     
  417.     def __bootstrap(self):
  418.         
  419.         try:
  420.             self._Thread__started = 1
  421.             _active_limbo_lock.acquire()
  422.             _active[_get_ident()] = self
  423.             del _limbo[self]
  424.             _active_limbo_lock.release()
  425.             if __debug__:
  426.                 self._note('%s.__bootstrap(): thread started', self)
  427.             
  428.             
  429.             try:
  430.                 self.run()
  431.             except SystemExit:
  432.                 if __debug__:
  433.                     self._note('%s.__bootstrap(): raised SystemExit', self)
  434.                 
  435.             except:
  436.                 __debug__
  437.                 if __debug__:
  438.                     self._note('%s.__bootstrap(): unhandled exception', self)
  439.                 
  440.                 s = _StringIO()
  441.                 _print_exc(file = s)
  442.                 _sys.stderr.write('Exception in thread %s:\n%s\n' % (self.getName(), s.getvalue()))
  443.  
  444.             if __debug__:
  445.                 self._note('%s.__bootstrap(): normal return', self)
  446.         finally:
  447.             self._Thread__stop()
  448.             self._Thread__delete()
  449.  
  450.  
  451.     
  452.     def __stop(self):
  453.         self._Thread__block.acquire()
  454.         self._Thread__stopped = 1
  455.         self._Thread__block.notifyAll()
  456.         self._Thread__block.release()
  457.  
  458.     
  459.     def __delete(self):
  460.         _active_limbo_lock.acquire()
  461.         del _active[_get_ident()]
  462.         _active_limbo_lock.release()
  463.  
  464.     
  465.     def join(self, timeout = None):
  466.         if not __debug__ and self._Thread__initialized:
  467.             raise AssertionError, 'Thread.__init__() not called'
  468.         if not __debug__ and self._Thread__started:
  469.             raise AssertionError, 'cannot join thread before it is started'
  470.         if not __debug__ and self is not currentThread():
  471.             raise AssertionError, 'cannot join current thread'
  472.         if __debug__:
  473.             if not (self._Thread__stopped):
  474.                 self._note('%s.join(): waiting until thread stops', self)
  475.             
  476.         
  477.         self._Thread__block.acquire()
  478.         if timeout is None:
  479.             while not (self._Thread__stopped):
  480.                 self._Thread__block.wait()
  481.             if __debug__:
  482.                 self._note('%s.join(): thread stopped', self)
  483.             
  484.         else:
  485.             deadline = _time() + timeout
  486.             while not (self._Thread__stopped):
  487.                 delay = deadline - _time()
  488.                 if delay <= 0:
  489.                     if __debug__:
  490.                         self._note('%s.join(): timed out', self)
  491.                     
  492.                     break
  493.                 
  494.                 self._Thread__block.wait(delay)
  495.             if __debug__:
  496.                 self._note('%s.join(): thread stopped', self)
  497.             
  498.         self._Thread__block.release()
  499.  
  500.     
  501.     def getName(self):
  502.         if not __debug__ and self._Thread__initialized:
  503.             raise AssertionError, 'Thread.__init__() not called'
  504.         return self._Thread__name
  505.  
  506.     
  507.     def setName(self, name):
  508.         if not __debug__ and self._Thread__initialized:
  509.             raise AssertionError, 'Thread.__init__() not called'
  510.         self._Thread__name = str(name)
  511.  
  512.     
  513.     def isAlive(self):
  514.         if not __debug__ and self._Thread__initialized:
  515.             raise AssertionError, 'Thread.__init__() not called'
  516.         if self._Thread__started:
  517.             pass
  518.         return not (self._Thread__stopped)
  519.  
  520.     
  521.     def isDaemon(self):
  522.         if not __debug__ and self._Thread__initialized:
  523.             raise AssertionError, 'Thread.__init__() not called'
  524.         return self._Thread__daemonic
  525.  
  526.     
  527.     def setDaemon(self, daemonic):
  528.         if not __debug__ and self._Thread__initialized:
  529.             raise AssertionError, 'Thread.__init__() not called'
  530.         if not __debug__ and not (self._Thread__started):
  531.             raise AssertionError, 'cannot set daemon status of active thread'
  532.         self._Thread__daemonic = daemonic
  533.  
  534.  
  535.  
  536. class _MainThread(Thread):
  537.     
  538.     def __init__(self):
  539.         Thread.__init__(self, name = 'MainThread')
  540.         self._Thread__started = 1
  541.         _active_limbo_lock.acquire()
  542.         _active[_get_ident()] = self
  543.         _active_limbo_lock.release()
  544.         
  545.         try:
  546.             self._MainThread__oldexitfunc = _sys.exitfunc
  547.         except AttributeError:
  548.             self._MainThread__oldexitfunc = None
  549.  
  550.         _sys.exitfunc = self._MainThread__exitfunc
  551.  
  552.     
  553.     def _set_daemon(self):
  554.         return 0
  555.  
  556.     
  557.     def _MainThread__exitfunc(self):
  558.         self._Thread__stop()
  559.         t = _pickSomeNonDaemonThread()
  560.         if t:
  561.             if __debug__:
  562.                 self._note('%s: waiting for other threads', self)
  563.             
  564.         
  565.         while t:
  566.             t.join()
  567.             t = _pickSomeNonDaemonThread()
  568.         if self._MainThread__oldexitfunc:
  569.             if __debug__:
  570.                 self._note('%s: calling exit handler', self)
  571.             
  572.             self._MainThread__oldexitfunc()
  573.         
  574.         if __debug__:
  575.             self._note('%s: exiting', self)
  576.         
  577.         self._Thread__delete()
  578.  
  579.  
  580.  
  581. def _pickSomeNonDaemonThread():
  582.     for t in enumerate():
  583.         pass
  584.     
  585.     return None
  586.  
  587.  
  588. class _DummyThread(Thread):
  589.     
  590.     def __init__(self):
  591.         Thread.__init__(self, name = _newname('Dummy-%d'))
  592.         self._DummyThread__Thread_started = 1
  593.         _active_limbo_lock.acquire()
  594.         _active[_get_ident()] = self
  595.         _active_limbo_lock.release()
  596.  
  597.     
  598.     def _set_daemon(self):
  599.         return 1
  600.  
  601.     
  602.     def join(self):
  603.         if not __debug__ and 0:
  604.             raise AssertionError, 'cannot join a dummy thread'
  605.  
  606.  
  607.  
  608. def currentThread():
  609.     
  610.     try:
  611.         return _active[_get_ident()]
  612.     except KeyError:
  613.         print 'currentThread(): no current thread for', _get_ident()
  614.         return _DummyThread()
  615.  
  616.  
  617.  
  618. def activeCount():
  619.     _active_limbo_lock.acquire()
  620.     count = len(_active) + len(_limbo)
  621.     _active_limbo_lock.release()
  622.     return count
  623.  
  624.  
  625. def enumerate():
  626.     _active_limbo_lock.acquire()
  627.     active = _active.values() + _limbo.values()
  628.     _active_limbo_lock.release()
  629.     return active
  630.  
  631. _MainThread()
  632.  
  633. def _test():
  634.     import random
  635.     
  636.     class BoundedQueue(_Verbose):
  637.         
  638.         def __init__(self, limit):
  639.             _Verbose.__init__(self)
  640.             self.mon = RLock()
  641.             self.rc = Condition(self.mon)
  642.             self.wc = Condition(self.mon)
  643.             self.limit = limit
  644.             self.queue = []
  645.  
  646.         
  647.         def put(self, item):
  648.             self.mon.acquire()
  649.             while len(self.queue) >= self.limit:
  650.                 self._note('put(%s): queue full', item)
  651.                 self.wc.wait()
  652.             self.queue.append(item)
  653.             self._note('put(%s): appended, length now %d', item, len(self.queue))
  654.             self.rc.notify()
  655.             self.mon.release()
  656.  
  657.         
  658.         def get(self):
  659.             self.mon.acquire()
  660.             while not (self.queue):
  661.                 self._note('get(): queue empty')
  662.                 self.rc.wait()
  663.             item = self.queue[0]
  664.             del self.queue[0]
  665.             self._note('get(): got %s, %d left', item, len(self.queue))
  666.             self.wc.notify()
  667.             self.mon.release()
  668.             return item
  669.  
  670.  
  671.     
  672.     class ProducerThread(Thread):
  673.         
  674.         def __init__(self, queue, quota):
  675.             Thread.__init__(self, name = 'Producer')
  676.             self.queue = queue
  677.             self.quota = quota
  678.  
  679.         
  680.         def run(self):
  681.             random
  682.             counter = 0
  683.             while counter < self.quota:
  684.                 counter = counter + 1
  685.                 self.queue.put('%s.%d' % (self.getName(), counter))
  686.                 _sleep(random() * 1e-005)
  687.                 continue
  688.                 import random
  689.  
  690.  
  691.     
  692.     class ConsumerThread(Thread):
  693.         
  694.         def __init__(self, queue, count):
  695.             Thread.__init__(self, name = 'Consumer')
  696.             self.queue = queue
  697.             self.count = count
  698.  
  699.         
  700.         def run(self):
  701.             while self.count > 0:
  702.                 item = self.queue.get()
  703.                 print item
  704.                 self.count = self.count - 1
  705.  
  706.  
  707.     import time
  708.     NP = 3
  709.     QL = 4
  710.     NI = 5
  711.     Q = BoundedQueue(QL)
  712.     P = []
  713.     for i in range(NP):
  714.         t = ProducerThread(Q, NI)
  715.         t.setName('Producer-%d' % (i + 1))
  716.         P.append(t)
  717.     
  718.     C = ConsumerThread(Q, NI * NP)
  719.     for t in P:
  720.         t.start()
  721.         _sleep(1e-006)
  722.     
  723.     C.start()
  724.     for t in P:
  725.         t.join()
  726.     
  727.     C.join()
  728.  
  729. if __name__ == '__main__':
  730.     _test()
  731.  
  732.