《操作系统》的实验代码。
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

43 lines
1.0 KiB

  1. #!/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #filename: peartest.py
  4. import threading, signal
  5. is_exit = False
  6. def doStress(i, cc):
  7. global is_exit
  8. idx = i
  9. while not is_exit:
  10. if (idx < 10000000):
  11. print "thread[%d]: idx=%d"%(i, idx)
  12. idx = idx + cc
  13. else:
  14. break
  15. if is_exit:
  16. print "receive a signal to exit, thread[%d] stop."%i
  17. else:
  18. print "thread[%d] complete."%i
  19. def handler(signum, frame):
  20. global is_exit
  21. is_exit = True
  22. print "receive a signal %d, is_exit = %d"%(signum, is_exit)
  23. if __name__ == "__main__":
  24. signal.signal(signal.SIGINT, handler)
  25. signal.signal(signal.SIGTERM, handler)
  26. cc = 5
  27. threads = []
  28. for i in range(cc):
  29. t = threading.Thread(target=doStress, args=(i,cc))
  30. t.setDaemon(True)
  31. threads.append(t)
  32. t.start()
  33. while 1:
  34. alive = False
  35. for i in range(cc):
  36. alive = alive or threads[i].isAlive()
  37. if not alive:
  38. break