fail_switch_two_greenlets.py 817 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. """
  2. Uses a trace function to switch greenlets at unexpected times.
  3. In the trace function, we switch from the current greenlet to another
  4. greenlet, which switches
  5. """
  6. import greenlet
  7. g1 = None
  8. g2 = None
  9. switch_to_g2 = False
  10. def tracefunc(*args):
  11. print('TRACE', *args)
  12. global switch_to_g2
  13. if switch_to_g2:
  14. switch_to_g2 = False
  15. g2.switch()
  16. print('\tLEAVE TRACE', *args)
  17. def g1_run():
  18. print('In g1_run')
  19. global switch_to_g2
  20. switch_to_g2 = True
  21. greenlet.getcurrent().parent.switch()
  22. print('Return to g1_run')
  23. print('Falling off end of g1_run')
  24. def g2_run():
  25. g1.switch()
  26. print('Falling off end of g2')
  27. greenlet.settrace(tracefunc)
  28. g1 = greenlet.greenlet(g1_run)
  29. g2 = greenlet.greenlet(g2_run)
  30. g1.switch()
  31. print('Falling off end of main')
  32. g2.switch()