thread_lock4.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. # test using lock to coordinate access to global mutable objects
  2. #
  3. # MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
  4. try:
  5. import utime as time
  6. except ImportError:
  7. import time
  8. import _thread
  9. def fac(n):
  10. x = 1
  11. for i in range(1, n + 1):
  12. x *= i
  13. return x
  14. def thread_entry():
  15. while True:
  16. with jobs_lock:
  17. try:
  18. f, arg = jobs.pop(0)
  19. except IndexError:
  20. return
  21. ans = f(arg)
  22. with output_lock:
  23. output.append((arg, ans))
  24. # create a list of jobs
  25. jobs = [(fac, i) for i in range(20, 80)]
  26. jobs_lock = _thread.allocate_lock()
  27. n_jobs = len(jobs)
  28. # create a list to store the results
  29. output = []
  30. output_lock = _thread.allocate_lock()
  31. # spawn threads to do the jobs
  32. for i in range(4):
  33. _thread.start_new_thread(thread_entry, ())
  34. # wait for the jobs to complete
  35. while True:
  36. with jobs_lock:
  37. if len(output) == n_jobs:
  38. break
  39. time.sleep(1)
  40. # sort and print the results
  41. output.sort(key=lambda x: x[0])
  42. for arg, ans in output:
  43. print(arg, ans)