fib.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #!/usr/bin/env python
  2. from twisted.internet import threads, reactor
  3. def largeFibonnaciNumber():
  4. """
  5. Represent a long running blocking function by calculating
  6. the TARGETth Fibonnaci number
  7. """
  8. TARGET = 10000
  9. # TARGET = 100000
  10. first = 0
  11. second = 1
  12. for i in range(TARGET - 1):
  13. new = first + second
  14. first = second
  15. second = new
  16. return second
  17. def fibonacciCallback(result):
  18. """
  19. Callback which manages the largeFibonnaciNumber result by
  20. printing it out
  21. """
  22. print("largeFibonnaciNumber result =", result)
  23. # make sure the reactor stops after the callback chain finishes,
  24. # just so that this example terminates
  25. reactor.stop()
  26. def run():
  27. """
  28. Run a series of operations, deferring the largeFibonnaciNumber
  29. operation to a thread and performing some other operations after
  30. adding the callback
  31. """
  32. # get our Deferred which will be called with the largeFibonnaciNumber result
  33. d = threads.deferToThread(largeFibonnaciNumber)
  34. # add our callback to print it out
  35. d.addCallback(fibonacciCallback)
  36. print("1st line after the addition of the callback")
  37. print("2nd line after the addition of the callback")
  38. if __name__ == '__main__':
  39. run()
  40. reactor.run()