thread_sleep1.py 612 B

12345678910111213141516171819202122232425262728293031
  1. # test threads sleeping
  2. #
  3. # MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
  4. try:
  5. import utime
  6. sleep_ms = utime.sleep_ms
  7. except ImportError:
  8. import time
  9. sleep_ms = lambda t: time.sleep(t / 1000)
  10. import _thread
  11. lock = _thread.allocate_lock()
  12. n_thread = 4
  13. n_finished = 0
  14. def thread_entry(t):
  15. global n_finished
  16. sleep_ms(t)
  17. sleep_ms(2 * t)
  18. with lock:
  19. n_finished += 1
  20. for i in range(n_thread):
  21. _thread.start_new_thread(thread_entry, (10 * i,))
  22. # wait for threads to finish
  23. while n_finished < n_thread:
  24. sleep_ms(100)
  25. print('done', n_thread)