thread_lock3.py 568 B

123456789101112131415161718192021222324252627
  1. # test thread coordination using a lock object
  2. #
  3. # MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
  4. import _thread
  5. lock = _thread.allocate_lock()
  6. n_thread = 10
  7. n_finished = 0
  8. def thread_entry(idx):
  9. global n_finished
  10. while True:
  11. with lock:
  12. if n_finished == idx:
  13. break
  14. print('my turn:', idx)
  15. with lock:
  16. n_finished += 1
  17. # spawn threads
  18. for i in range(n_thread):
  19. _thread.start_new_thread(thread_entry, (i,))
  20. # busy wait for threads to finish
  21. while n_finished < n_thread:
  22. pass