Advertisement
GoodiesHQ

Threading_Tutorial_02.py

Mar 20th, 2017
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.91 KB | None | 0 0
  1. import time
  2. import threading
  3.  
  4. class PrintFactorial(threading.Thread):
  5.     def __init__(self, n):
  6.         super(PrintFactorial, self).__init__()      # call the original threading.Thread constructor
  7.         self.n = n                                  # user-provided n value whose factorial value will be calculated in a new thread
  8.  
  9.     def run(self):
  10.         """The 'run' method is a classmethod that will be run within a new thread.
  11.        Because the return value is not stored, we are printing the value to stdout."""
  12.         val = 1
  13.         while self.n > 1:
  14.             val *= self.n
  15.             self.n -= 1
  16.         print(val)
  17.  
  18. pf = PrintFactorial(33733)                          # creates a new instance of the above class
  19. pf.start()                                          # executes the above run method in a new thread
  20. print("Calculating... Awaiting ")                   # this occurs in the main thread
  21. pf.join()                                           # blocks execution of the main thread until the run function is complete
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement