thread_exc1.py 564 B

123456789101112131415161718192021222324252627282930
  1. # test raising and catching an exception within a thread
  2. #
  3. # MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
  4. import _thread
  5. def foo():
  6. raise ValueError
  7. def thread_entry():
  8. try:
  9. foo()
  10. except ValueError:
  11. pass
  12. with lock:
  13. global n_finished
  14. n_finished += 1
  15. lock = _thread.allocate_lock()
  16. n_thread = 4
  17. n_finished = 0
  18. # spawn threads
  19. for i in range(n_thread):
  20. _thread.start_new_thread(thread_entry, ())
  21. # busy wait for threads to finish
  22. while n_finished < n_thread:
  23. pass
  24. print('done')