Advertisement
rfmonk

decimal_thread_context.py

Jan 22nd, 2014
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.80 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3.  
  4. import decimal
  5. import threading
  6. from Queue import PriorityQueue
  7.  
  8.  
  9. class Multiplier(threading.Thread):
  10.     def __init__(self, a, b, prec, q):
  11.         self.a = a
  12.         self.b = b
  13.         self.prec = prec
  14.         self.q = q
  15.         threading.Thread.__init__(self)
  16.  
  17.     def run(self):
  18.         c = decimal.getcontext().copy()
  19.         c.prec = self.prec
  20.         decimal.setcontext(c)
  21.         self.q.put((self.prec, a * b))
  22.         return
  23.  
  24. a = decimal.Decimal('3.14')
  25. b = decimal.Decimal('1.234')
  26. # A PriorityQueue will return values sorted by precision
  27. # no matter what the threads finish.
  28. q = PriorityQueue()
  29. threads = [Multiplier(a, b, i, q) for i in range(1, 6)]
  30. for t in threads:
  31.     t.start()
  32.  
  33. for t in threads:
  34.     t.join()
  35.  
  36. for i in range(5):
  37.     prec, value = q.get()
  38.     print prec, '\t', value
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement