thread_shared2.py 712 B

1234567891011121314151617181920212223242526272829303132
  1. # test capability for threads to access a shared mutable data structure
  2. # (without contention because they access different parts of the structure)
  3. #
  4. # MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
  5. import _thread
  6. def foo(lst, i):
  7. lst[i] += 1
  8. def thread_entry(n, lst, idx):
  9. for i in range(n):
  10. foo(lst, idx)
  11. with lock:
  12. global n_finished
  13. n_finished += 1
  14. lock = _thread.allocate_lock()
  15. n_thread = 2
  16. n_finished = 0
  17. # the shared data structure
  18. lst = [0, 0]
  19. # spawn threads
  20. for i in range(n_thread):
  21. _thread.start_new_thread(thread_entry, ((i + 1) * 10, lst, i))
  22. # busy wait for threads to finish
  23. while n_finished < n_thread:
  24. pass
  25. print(lst)