thread_shared1.py 603 B

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